Tracking Email Opens in Laravel

Posted on September 29, 2017
Laravel Email

Recently I had the need for a bulk emailing service. I did not want to pay for one so I threw one together quick with Laravel and Gmail SMTP.

One of the features I needed was the ability to see when a lead opened the email. This is how I did it.

The Tracking Pixel #

In order to track opens, you need to be able to make a request to your server to let it know someone opened the email.

I did this by creating a 1px by 1px GIF image and creating an open API GET endpoint. This is what the controller looked like:

public function store()
{
  return response(file_get_contents(public_path('./img/pixel.gif')))
    ->header('content-type', 'image/gif');
}

All this does is return the GIF so I can embed it in the email.

But I also need to be able to save this somewhere. So I created an Activity model and added that to the controller:

public function store()
{
  Activity::create();

  return response(file_get_contents(public_path('./img/pixel.gif')))
    ->header('content-type', 'image/gif');
}

So now I know when a lead opens the email.

But I also wanted to know what lead opened the email and which Campaign it was from.

So I added the lead_id and the campaign_id to the Activity:

public function store(Campaign $campaign, Lead $lead)
{
  Activity::create([
    'campaign_id' => $campaign->id,
    'lead_id' => $lead->id,
  ]);

  return response(file_get_contents(public_path('./img/pixel.gif')))
    ->header('content-type', 'image/gif');
}

Which gives us the final method.

Now when I send the email I just need to add the pixel image like this:

<img src="http://example.com/api/opens/{campaign_id}/{lead_id}" /> <!-- NO ALT TEXT -->

Don't add the alt attribute or email apps with images turned off will see the alt text.

Wrapping up #

This is a super simple technique that is pretty easy to implement. The data collected can be used to analyze what emails are more successful than others and gives you the opportunity to add some charts to a dashboard ????.

I am working on a bulk emailing solution for myself it will have tracking and more if it works out I might release it to the public.

If you have any questions about this article hit me up on twitter @sampodlogar.