. */ declare(strict_types=1); namespace App\EventSubscriber; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Mailer\Event\MessageEvent; use Symfony\Component\Mime\Address; use Symfony\Component\Mime\Email; /** * This subscriber set the "From" field for all sent email, based on the global configured sender name and email. */ final class SetMailFromSubscriber implements EventSubscriberInterface { private string $email; private string $name; public function __construct(string $email, string $name) { $this->email = $email; $this->name = $name; } public function onMessage(MessageEvent $event): void { $address = new Address($this->email, $this->name); $event->getEnvelope()->setSender($address); $email = $event->getMessage(); if ($email instanceof Email) { $email->from($address); } } public static function getSubscribedEvents(): array { return [ // should be the last one to allow header changes by other listeners first MessageEvent::class => ['onMessage'], ]; } }