Log all your emails like a boss

Tip published on December 5, 2016 by @markvaneijk in Laravel

One of the things I like to do is to make sure my app saves everything it does to the database for later review. So for example when the app sends an email, I would like to check if, and when it did and to whom, so everything I could possibly want to know.

It's very important to be able to trace back when things occur and if your app did what you expected it to do, especially when your working for your clients, but also for your own sake!

With Laravel it's very easy to do. In three steps: Create a LogMail event, register it in the service provider and create an Eloquent model for saving it to the database.

1. Create the event listener

Create this LogMail class in app/Events/Listeners/LogMail.php:

<?php

namespace App\Events\Listeners;

use App\Mail;

class LogMail
{
    public function handle($event)
    {
        Mail::create([
            'from' => $event->message->getFrom(),
            'sender' => $event->message->getSender(),
            'replyto' => $event->message->getReplyTo(),
            'to' => $event->message->getTo(),
            'cc' => $event->message->getCc(),
            'bcc' => $event->message->getBcc(),
            'subject' => $event->message->getSubject(),
            'body' => $event->message->getBody(),
        ]);
    }
}

2. Register the Event in the Service Provider

Register it in the app/Providers/EventServiceProvider.php file for listening for the "MessageSending" event:

<?php

protected $listen = [
    'Illuminate\Mail\Events\MessageSending' => [
        \App\Events\Listeners\LogMail::class
    ],
];

3. Make an Eloquent model

The Eloquent model in simplest and minimal form in the app folder:

<?php

namespace App;

use Eloquent;

class Mail extends Eloquent
{
    protected $fillable = [
        'from', 'sender', 'replyto', 'to', 'cc', 'bcc', 'subject', 'body'
    ];
}

And your good to go!