. */ 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 { public function __construct(private readonly string $email, private readonly string $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'], ]; } }