Symfony - Get the state of the mail sended with Messenger

188 Views Asked by At

I'm currently using Symfony Messenger on my project. I'm using it to send mails through the MessageHandler

Heres the file :

<?php

namespace App\MessageHandler;

use App\Entity\Dossier;
use App\Message\SendEmailMessage;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

class SendEmailMessageHandler implements MessageHandlerInterface
{
    /** @var EntityManagerInterface */
    private $em;
    /** @var MailerInterface */
    private $mailer;

    public function __construct(EntityManagerInterface $entityManager, MailerInterface $mailer)
    {
        $this->entityManager = $entityManager;
        $this->mailer = $mailer;
    }

    public function __invoke(SendEmailMessage $message)
    {
        $email = (new Email())
        ->from('[email protected]')
        ->to('[email protected]')
        ->subject('test')
        ->html('test');

        $this->mailer->send($email);
    }

}

Is it a way to track the mail through Messenger to get a response from the smtp server or something like this ? I'd like to show the user if the mail was sent or not using Messenger

1

There are 1 best solutions below

4
Jason Olson On

You can track if the message failed when being handed off to the SMTP server through a try/catch block as showing at https://symfony.com/doc/current/mailer.html#handling-sending-failures


$email = new Email();
// ...
try {
    $mailer->send($email);
} catch (TransportExceptionInterface $e) {
    // some error prevented the email sending; display an
    // error message or try to resend the message
}

However, if you're looking for further feedback, such as if the message was ultimately undeliverable (bounce, full mailbox, etc) then you'll want to look either into the management side of your mail server, or more into third-party transports, that will then issue a callback webhook that will later inform you of the status. Those service also provide great feedback such as if your message was marked spam by the recipient, etc.