BLOG // May 3, 2021

SendGrid custom headers with Laravel Mail

SendGrid allows an easy way to add custom properties to their Activity Tracking and Marketing/Webhook integrations using their X-SMTPAPI header. Our use case for this is tagging invite and signup emails and doing some analytics on their delivery rate, etc.

It's made extremely easy by Laravel, and you can edit any app/Mail mailable and alter your build() function. You can see an example of mine below:

public function build()
    {
        $customHeader = '{
            "category": "Example",
            "unique_args": {
                "mailType": "Signup"
            }
        }';

        $this->withSwiftMessage(function ($message) use ($customHeader) {
            $message->getHeaders()->addTextHeader('X-SMTPAPI', $customHeader);
        });

        return $this->markdown('emails.signup.pending');
    }

Category is always present in the SendGrid system, but you can put key=>value objects you want in the unique_args option and they will be tracked and queryable on SendGrid. In our example we set mailType to 'Signup'.

You can also achieve this with a tweak to Mail::send calls:

Mail::send('view.name', $data, function ($message) {
    $customHeader = '{
        "category": "Example",
        "unique_args": {
            "mailType": "Signup"
        }
    }';

    $message->getHeaders()->addTextHeader('X-SMTPAPI', $customHeader);
});

This technique can be used to add any headers to Laravel SMTP emails of course, but is especially useful with SendGrid.

Comments

Subscribe to new articles

If you enjoy my content, consider subscribing. You will only receive new blog stories, no other email.