Laravel doesn't support Monolog with Symfony Mailer natively as of June 2022. However, using the monolog
driver in the logging config allows to configure this manually.
First, you need to add symfony/mailer
as a dependency: composer require symfony/mailer
In logging.php
, you can create a new channel that looks like this:
'mail' => [ // create a channel with the identifier `mail`
'driver' => 'monolog', // use this driver to use Handlers that are not included in Laravel
'handler' => Monolog\Handler\SymfonyMailerHandler::class,
'level' => 'error',
'with' => [ // initialize the Handler with these options
// Configure the Mailer to use SMTP and provide it with the credentials for the SMTP server.
// You may also use other protocols. For more info: https://symfony.com/doc/current/mailer.html#transport-setup
// In this case, I build the DSN from the environment variables which Laravel includes by default.
'mailer' => new Symfony\Component\Mailer\Mailer(Symfony\Component\Mailer\Transport::fromDsn(
'smtp://'.urlencode(env('MAIL_USERNAME')).':'.urlencode(env('MAIL_PASSWORD')).'@'.env('MAIL_HOST').':'.env('MAIL_PORT'))),
'email' => fn ($content, $records) => (new Email())
->subject('error occurred')
->from('from@example.com')
->to('to@example.com'),
],
],
Note that we create the Mailer manually, although Laravel should be doing the same internally somewhere. However, while the config is read, the Mailer is not yet instantiated. I believe it doesn't get any prettier until Laravel supports this natively.
Now you can configure Laravel to use the mail
log channel. For example, you could set the default log channel to mail
in logging.php
.
When tinkering with the mail log channel, make sure to disable the mail channel during tests. I disabled logging completely in phpunit.xml
:
<server name="LOG_CHANNEL" value="'null'"/>