Mailer.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. public function __construct(
  25. private TransportInterface $transport,
  26. private ?MessageBusInterface $bus = null,
  27. private ?EventDispatcherInterface $dispatcher = null,
  28. ) {
  29. }
  30. public function send(RawMessage $message, ?Envelope $envelope = null): void
  31. {
  32. if (null === $this->bus) {
  33. $this->transport->send($message, $envelope);
  34. return;
  35. }
  36. $stamps = [];
  37. if (null !== $this->dispatcher) {
  38. // The dispatched event here has `queued` set to `true`; the goal is NOT to render the message, but to let
  39. // listeners do something before a message is sent to the queue.
  40. // We are using a cloned message as we still want to dispatch the **original** message, not the one modified by listeners.
  41. // That's because the listeners will run again when the email is sent via Messenger by the transport (see `AbstractTransport`).
  42. // Listeners should act depending on the `$queued` argument of the `MessageEvent` instance.
  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. $stamps = $event->getStamps();
  48. if ($event->isRejected()) {
  49. return;
  50. }
  51. }
  52. try {
  53. $this->bus->dispatch(new SendEmailMessage($message, $envelope), $stamps);
  54. } catch (HandlerFailedException $e) {
  55. foreach ($e->getWrappedExceptions() as $nested) {
  56. if ($nested instanceof TransportExceptionInterface) {
  57. throw $nested;
  58. }
  59. }
  60. throw $e;
  61. }
  62. }
  63. }