vendor/symfony/mailer/Mailer.php line 35

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Mailer;
  11. use Psr\EventDispatcher\EventDispatcherInterface;
  12. use Symfony\Component\EventDispatcher\Event;
  13. use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
  14. use Symfony\Component\Mailer\Event\MessageEvent;
  15. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  16. use Symfony\Component\Mailer\Messenger\SendEmailMessage;
  17. use Symfony\Component\Mailer\Transport\TransportInterface;
  18. use Symfony\Component\Messenger\Exception\HandlerFailedException;
  19. use Symfony\Component\Messenger\MessageBusInterface;
  20. use Symfony\Component\Mime\RawMessage;
  21. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as SymfonyEventDispatcherInterface;
  22. /**
  23. * @author Fabien Potencier <fabien@symfony.com>
  24. */
  25. final class Mailer implements MailerInterface
  26. {
  27. private $transport;
  28. private $bus;
  29. private $dispatcher;
  30. public function __construct(TransportInterface $transport, MessageBusInterface $bus = null, EventDispatcherInterface $dispatcher = null)
  31. {
  32. $this->transport = $transport;
  33. $this->bus = $bus;
  34. $this->dispatcher = class_exists(Event::class) && $dispatcher instanceof SymfonyEventDispatcherInterface ? LegacyEventDispatcherProxy::decorate($dispatcher) : $dispatcher;
  35. }
  36. public function send(RawMessage $message, Envelope $envelope = null): void
  37. {
  38. if (null === $this->bus) {
  39. $this->transport->send($message, $envelope);
  40. return;
  41. }
  42. if (null !== $this->dispatcher) {
  43. $clonedMessage = clone $message;
  44. $clonedEnvelope = null !== $envelope ? clone $envelope : Envelope::create($clonedMessage);
  45. $event = new MessageEvent($clonedMessage, $clonedEnvelope, (string) $this->transport, true);
  46. $this->dispatcher->dispatch($event);
  47. }
  48. try {
  49. $this->bus->dispatch(new SendEmailMessage($message, $envelope));
  50. } catch (HandlerFailedException $e) {
  51. foreach ($e->getNestedExceptions() as $nested) {
  52. if ($nested instanceof TransportExceptionInterface) {
  53. throw $nested;
  54. }
  55. }
  56. throw $e;
  57. }
  58. }
  59. }