1

i'm trying to write a log when my app in symfony 5.4 send an email. But it seems that the MessageEvent is never fired.

In the console the EventListener seem to be registered correctly:

# bin/console debug:event-dispatcher

Registered Listeners Grouped by Event

"Symfony\Component\Mailer\Event\MessageEvent" event


Order Callable Priority


#1 App\EventSubscriber\MailerLoggerSubscriber::onMessage() 0
#2 Symfony\Component\Mailer\EventListener\MessageListener::onMessage() 0
#3 Symfony\Component\Mailer\EventListener\EnvelopeListener::onMessage() -255
#4 Symfony\Component\Mailer\EventListener\MessageLoggerListener::onMessage() -255


Here my EventListener:

<?php

namespace App\EventSubscriber;

use App\Entity\MailLog;
use App\Repository\MailLogRepository;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Mailer\Event\MessageEvent;

class MailerLoggerSubscriber implements EventSubscriberInterface
{
   protected MailLogRepository $mailerRepository;
   protected EntityManagerInterface $entityManager;
   protected LoggerInterface $logger;

   public function __construct(MailLogRepository 
   $mailerRepository,EntityManagerInterface $entityManager, LoggerInterface $logger)
   {
       $this->mailerRepository = $mailerRepository;
       $this->entityManager = $entityManager;
       $this->logger = $logger;
   }

public static function getSubscribedEvents()
{
    return [
        MessageEvent::class => ['onMessage', -255],
    ];
}


public function onMessage(MessageEvent $event): void
{

    $message = $event->getMessage();

    // do nothing with a spooled messages, there comes a second send event
    /*if ($this->getReadableResult($event) === 'spooled') {
        return false;
    }*/
    $envelope = $event->getEnvelope();
    $fromAddresses = [];
    foreach ($envelope->getSender() as $add) {
        $fromAddresses[] = $add;
    }

    $toAddresses = [];
    foreach ($envelope->getRecipients() as $add) {
        $toAddresses[] = $add;
    }

    $mailLog = new MailLog();
    $mailLog->setSentAt(new \DateTime());
    $mailLog->setFrom(array_keys($fromAddresses));
    $mailLog->setTo(array_keys($toAddresses));
    $mailLog->setSubject('subject');
    $mailLog->setMessage($event->getMessage()->toString());
    $mailLog->setResult('success');

    $this->entityManager->persist($mailLog);
    $this->entityManager->flush();
}

}

Bellu
  • 2,575
  • 2
  • 22
  • 29

0 Answers0