vendor/symfony/mailer/Mailer.php line 39

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\Mailer\Event\MessageEvent;
  13. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  14. use Symfony\Component\Mailer\Messenger\SendEmailMessage;
  15. use Symfony\Component\Mailer\Transport\TransportInterface;
  16. use Symfony\Component\Messenger\Exception\HandlerFailedException;
  17. use Symfony\Component\Messenger\MessageBusInterface;
  18. use Symfony\Component\Mime\RawMessage;
  19. /**
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. */
  22. final class Mailer implements MailerInterface
  23. {
  24. private TransportInterface $transport;
  25. private ?MessageBusInterface $bus;
  26. private ?EventDispatcherInterface $dispatcher;
  27. public function __construct(TransportInterface $transport, MessageBusInterface $bus = null, EventDispatcherInterface $dispatcher = null)
  28. {
  29. $this->transport = $transport;
  30. $this->bus = $bus;
  31. $this->dispatcher = $dispatcher;
  32. }
  33. public function send(RawMessage $message, Envelope $envelope = null): void
  34. {
  35. if (null === $this->bus) {
  36. $this->transport->send($message, $envelope);
  37. return;
  38. }
  39. if (null !== $this->dispatcher) {
  40. // The dispatched event here has `queued` set to `true`; the goal is NOT to render the message, but to let
  41. // listeners do something before a message is sent to the queue.
  42. // We are using a cloned message as we still want to dispatch the **original** message, not the one modified by listeners.
  43. // That's because the listeners will run again when the email is sent via Messenger by the transport (see `AbstractTransport`).
  44. // Listeners should act depending on the `$queued` argument of the `MessageEvent` instance.
  45. $clonedMessage = clone $message;
  46. $clonedEnvelope = null !== $envelope ? clone $envelope : Envelope::create($clonedMessage);
  47. $event = new MessageEvent($clonedMessage, $clonedEnvelope, (string) $this->transport, true);
  48. $this->dispatcher->dispatch($event);
  49. }
  50. try {
  51. $this->bus->dispatch(new SendEmailMessage($message, $envelope));
  52. } catch (HandlerFailedException $e) {
  53. foreach ($e->getNestedExceptions() as $nested) {
  54. if ($nested instanceof TransportExceptionInterface) {
  55. throw $nested;
  56. }
  57. }
  58. throw $e;
  59. }
  60. }
  61. }