To gather the response code and message when sending emails using Symfony Mailer, you can utilize the Symfony\Component\Mailer\Event\MessageEvent and Symfony\Component\Mailer\EventListener\MessageLoggerListener. These components allow you to listen to events and capture the response details.
Here's a step-by-step guide on how to achieve this:
-
Register the Event Listener:
First, you need to register an event listener that will listen to the
MessageEvent. This can be done in your Symfony service configuration. -
Create a Custom Event Listener:
Create a custom event listener class that will handle the
MessageEventand extract the response details.namespace App\EventListener; use Symfony\Component\Mailer\Event\MessageEvent; use Symfony\Component\Mailer\EventListener\MessageLoggerListener; use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport; class MailerResponseListener { public function onMessageEvent(MessageEvent $event) { $transport = $event->getTransport(); if ($transport instanceof EsmtpTransport) { $lastResponse = $transport->getLastResponse(); if ($lastResponse) { $responseCode = $lastResponse->getCode(); $responseMessage = $lastResponse->getMessage(); // Log or handle the response code and message as needed // For example, you can log them: // $this->logger->info('SMTP Response', ['code' => $responseCode, 'message' => $responseMessage]); } } } } -
Register the Listener in Services Configuration:
Register your custom listener in the
services.yamlor equivalent configuration file.services: App\EventListener\MailerResponseListener: tags: - { name: 'kernel.event_listener', event: 'mailer.message_sent', method: 'onMessageEvent' } -
Use the Listener:
With the listener registered, it will automatically capture the response code and message whenever an email is sent using the Symfony Mailer.
This setup allows you to capture the SMTP response code and message for each email sent, regardless of whether an exception occurs. You can then log or handle these details as needed in your application.