Logging Email with Laravel

Laravel provides the Mail facade (as of version 5.6) which acts as a wrapper around the PHP email library Swift Mailer.

Any application that sends emails needs to have logging for send events. No one wants to go wading through Linux sendmail logs or bothering sysadmins to go through Exchange logs.

Swift Mailer provides a couple of different logging plugins natively. Laravel provides decent documentation around their Mail facade but omit some details. One feature they leave out are Swift Mailer’s plugins and how to access them using the wrapper.

$logger = new \Swift_Plugins_Loggers_ArrayLogger();
Mail::getSwiftMailer()->;registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));
$logger->dump()

The output of that log dump will look like this:

[2018-04-19 16:47:50] local.ERROR: ++ Starting Swift_SmtpTransport
<< 220 NORC142-E745-KS.someinstitute.edu ESMTP SubEthaSMTP null

>> EHLO [127.0.0.1]

<< 250-NORC142-E745-KS.someinstitute.edu
250-8BITMIME
250-AUTH LOGIN
250 Ok

++ Swift_SmtpTransport started
>> MAIL FROM:<application@someinstitute.edu>

<< 250 Ok

>> RCPT TO:<application@someinstitute.edu>

<< 250 Ok

>> DATA

<< 354 End data with <CR><LF>.<CR><LF>

>> 
.

<< 250 Ok

++ Stopping Swift_SmtpTransport
>> QUIT

<< 221 Bye

++ Swift_SmtpTransport stopped  

You only want to log this level of detail if you know the operation failed so you will probably put this in a try/catch statement. You can check out the documentation for Swift Mailer’s plugins at their documentation.

Thanks to http://www.purepixel.co.uk/2013/06/using-swift-mailer-plugins-with-laravel-4/ for mentioning this for an earlier version of Laravel.

Further Reading:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.