/ Node.js

Send email with Sendgrid from Node.js with Google Analytics tracking

Sendgrid is a great email service for any project that needs to send transactional emails. Compared to the well know Mailchimp, Sendgrid is geared more towards technical people that love to have a lot of options to tinker with. In that regard, I've always been more comfortable working with Sendgrid that any other service and in this post I'm going to show you have to integrate Sendgrid in your Node.js project. I'm also going to show you, even though Sendgrid has great built-in tracking features, to implement email tracking yourself using Google Analytics.

Setting up your project

The basics of sending an email with Sendgrid will work in any Node.js project, regardless of which framework you use. So I'm going to skip setting up a new project and assume you want to implement this into an existing project you have. First, we need to install the Sendgrid NPM package:

npm install --save @sendgrid/mail

In order to be able to send emails from a Sendgrid account and to authenticate we need an API Key. Go to API Keys under Settings in your sendgrid account and create a key. You can choose to create a key with full access, or if you want to be more secure you can create a key with just enough rights to send outgoing emails. Also don't forget to copy and store your key somewhere safe as your key will be shown only once.

sendgrid_api_key

Sending out an email

With the installed library and your API key at hand sending out an email is really simple. Import the library where you want to use it, set the API key, create a message and send it out:

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey('YOUR_KEY');

let msg = {
        to: 'egon@ghostbusters.com',
        from: 'hello@glamdevhero.com',
        subject: 'I need your help',
        html: '<strong>I am being chased by a ghost, help me!</strong>'
    };

sgMail.send(msg);

The above snippet will send out an HTML email to my favourite Ghostbuster, but as you can notice, the HTML is very basic and it wouldn't be very neat to just dump an entire HTML email template in the message object. You might have multiple email templates that are dynamically chosen, and maybe you'll also want to replace some variables inside the template to make it more personal. So let's rewrite this snippet so that it loads an HTML template:

const fs = require('fs');
const path = require("path");
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey('YOUR_KEY');

fs.readFile(path.resolve(__dirname, 'templates/amber-intro.html'), 'utf8', function(err, template) {
        template = template.replace('*|NAME|*', 'Egon Spengler');
        let msg = {
            to: 'egon@ghostbusters.com',
            from: 'hello@glamdevhero.com',
            subject: 'I need your help',
            html: template,
        };
        sgMail.send(msg);
});

We've added to imports in order to deal with the file system and create a relative path to our template folder that holds our email templates. I've also replaced a variable inside my mail template so I can send a more personal email.

Add tracking with Google Analytics

Usually, with emails, there are two things you want to track: opens and clicks. For each one we're going to use a different technique. To tracks clicks we're going to use UTM parameters. These are just a collection of parameters to you add to every outgoing link in your email. Here's an example:

https://www.glamdevhero.com/?utm_source=newsletter&utm_medium=email&utm_campaign=july_08

These parameters will be processed by Google Analytics everytime someone clicks that link and this data will show up in both your acquisition reports and campaign reports. Or you could create a custom report with the campaign name you chose as your primary dimension. If you're not sure how to create us UTM enabled links, Google has a great tool help you.

To track opens we will use the Google Analytics Measurement Protocol. This technique was created to send data to Google Analytics in environments where Javascript is not available. And although it can be used for offline tracking and server-side tracking, it is primarily used to track emails. To use the Measurement Protocol in an email we need to create a pixel request with a few additional parameters:

<img src="https://www.google-analytics.com/collect?v=1&..."/>

There's a couple of required parameters for any Measurement Protocol request. That's the Version, your Tracking ID and a Client ID. The version is always set to 1, the tracking id is the same ID you use in your standard tracking code and the client id is a unique string to identify a user. For the client id you can just create a random string or hash the user's email address.

For email tracking, we also want to add some additional parameters so we have a complete view in our reports. We want to add event data, campaign data and a document title. As we want this request to be processed as an event we need to set the request type as Event and set an event category and action. We generally use email as the category and open as the action. Also we will set the same campaign parameters as with our click tracking so clicks and opens can be associated with each other. And finally, we will set the Document Title to the subject of the email. Here's a complete example:

<img src="https://www.google-analytics.com/collect?v=1&t=event&tid=UA-XXXXX-XX&cid=RANDOM_STRING&ec=email&ea=open&dt=email_subject&cm=email&cn=july_08"/>

Adding this snippet to the bottom of your email template just before the closing body tag enables you to track opens in Google Analytics. And, of course, you are not limited to the parameters in the example. If you want to send more data you can check out the Measurement Protocol Reference and discover what else you can send along.

Nicolas Lierman

Nicolas Lierman

The original glamdevhero. Digital Innovation Architect at MultiMinds and interested in all things analytics, data and web development.

Read More
Send email with Sendgrid from Node.js with Google Analytics tracking
Share this

Subscribe and get the good stuff