Adding Mandrill tags to your Laravel email

The problem

When using Laravel mail with Mandrill as the mail driver you can send mails the Laravel way, just by adding the API key to your env file.

It works great but what if you use one Mandrill account for all your clients and you have to keep track of the number of emails send for each client?

API keys

The first thing coming to your mind will probably be to create an API key for each client. Which is great to see the difference in your outbound dashboard in Mandrill.

But using these api keys does not allow you to see how many emails you have sent with it, therefore we will need tags.

Mandrill tags

Using tags within Mandrill allows you to see how many emails you have sent with that tag. Besides creating an api key for each client, you also create a tag for them.

Attaching Mandrill tags using Mail::send(…);

Mandrill has a powerful api to send mail templates where you can also specify those tags. But we don’t want to use that api, we want to use the build in Laravel mail functionality.

According to the following Mandrill docs  you can also send tags using http headers. That’s great since Laravel allows you to add additional headers to emails.

Eventually, you will end up with a mail function similar to the following one:

Mail::send('your-mail-viewl', [], function($message) {
    $message->to('info@example.com');
    $message->subject('Subjectline');
    $message->getSwiftMessage()
        ->getHeaders()
        ->addTextHeader('X-MC-Tags', 'my-laravel-tag', 'my-second-laravel-tag');
});

You can even add multiple tags just by separating them with a comma.