laravelsymfony

Debug Laravel Mail Sending in Laravel 11 including SMTP Dialog


We are looking for a code snipped to test a Laravel mail SMTP while printing out the SMTP dialog. The SMTP dialog usually contains the message ID, so in case a mail does not reach it can be traced on the involved server.

In previous Laravel versions we used

$to = 'foo@example.com';

Mail::getSwiftMailer()->registerPlugin(   new Swift_Plugins_LoggerPlugin( new Swift_Plugins_Loggers_EchoLogger(false) ));

Mail::raw('Testmail', function ($message) use ($to) {  $message->to($to)->subject('Testmail'); });

This leads to

 BadMethodCallException  Method Illuminate\Mail\Mailer::getSwiftMailer does not exist.

How can this be ported to Laravel 11 which uses Symfony mailer?

Tried a bit with ChatGPT but no luck so far.


Solution

  • Based on Nico's answer, I came up with the following snipped which can easily be pasted to php artisan tinker to debug mail delivery of a Laravel 9+ appication:

    $to = 'foo@example.com';
    
    \Illuminate\Support\Facades\Event::listen(function (\Illuminate\Mail\Events\MessageSent $event) {
        echo "Message-ID\n";
        echo $event->sent->getSymfonySentMessage()->getMessageId() . "\n";
        echo "SMTP Dialog:\n";
        echo $event->sent->getSymfonySentMessage()->getDebug() . "\n";
    });
    \Illuminate\Support\Facades\Mail::raw('Testmail', function ($message) use ($to) {
        $message->to($to)->subject('Testmail ' . date('Y-m-d H:i:s'));
    });