Sending branded emails from Node.js

Branded transactional email can be a pain for a startup. They’re one of those items that can end up being a lot of work for something that feels like it should be included out of the box.

Don’t get stuck in email purgatory

Luckily, offerings like SendGrid and Mailchimp’s Mandrill promise to take this off our plates. Unfortunately, the process of getting started isn’t always as good a DX as you would hope.

You should be able to:

  • Create an email template online in a nice drag and drop interface
  • Trigger that email from my server whenever I want, along with some custom fields to be replaced in the email.

Here’s a quick guide on how to do exactly that with Sendgrid.

Sendgrid API

Go and sign up for account at Sendgrid and generate and API Key for your server. Copy it and save it for later.

Creating the template

Head to the Templates section. Give your template a unique name and then click Actions > Add version. You should now be in the WYSIWYG editor. Toggle ON the drag and drop editor if you so desire. Tap on the BUILD tab and create yourself a beautiful email.

Once you’re done, make a note of the long alpha-numeric Template ID, you’ll need it for your server code.

Substitutions

Anywhere you want custom information to appear in your email (e.g. firsName) you’ll need to use a substitution variable. You can use a couple of different formats for these but I’ve found the best is %variableName%.

NOTE: If for some reason the editor sticks html tags or encoding in the middle of your variable name, it’s not going to work. So if you find that a particular variable isn’t being substituted, check the HTML source of your template.

Building the email on the server

Official Sendgrid npm package:
https://www.npmjs.com/package/sendgrid

npm install --save sendgrid

It’s good practice to save your API Key outside of your codebase as part of your environment variables. Or if you’re using Meteor in your settings.json file.

Here is some heavily commented example code using ES6 imports. The npm package page has examples for require. The first import is the main library, and the second is a bunch of helpers we’ll use to build the email.

import Sendgrid from 'sendgrid';
import * as helper from 'sendgrid/lib/helpers/mail/mail';
// Create a mailer
const mailer = Sendgrid(SENDGRID_KEY);
// Create the email object
const email = new helper.Mail();
// Set the from address
const fromEmail = new helper.Email('info@flyblackbird.com');
email.setFrom(fromEmail);
// Set the email subject
email.setSubject('Welcome!');
// Set the content - even if your template doesn't use content, the API requires at least one character to be sent
const content = new helper.Content('text/html', 'Template');
email.addContent(content);
// Create some personalization for the email
const personalization = new helper.Personalization();
// Add a to address
const toEmail = new helper.Email('jamie@beautifulcoding.com');
personalization.addTo(toEmail);
// Add a substitution for our template
const firstName = new helper.Substitution('%firstName%', 'Jamie');
personalization.addSubstitution(firstName);
// Add all of these personalizations to the email
email.addPersonalization(personalization);
// Specify which template you want to use
email.setTemplateId(SENDGRID_TEMPLATE_ID);
// Put everything together into an email request object
const request = mailer.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: email.toJSON(),
});
// Send the email!
mailer.API(request, (e, response) => {
console.log(response.statusCode);
console.log(response.body);
console.log(response.headers);
});

Conclusion

Sendgrid are working on Phase 2 of their v3 API overhaul and hopefully that will bring some better DX, but as it stands currently, with a little work up front, you should be sending beautiful emails in no time. At Blackbird we’ve rolled our own helpers on top of this to keep things tidy, quick and easy.

Useful links

The Sendgrid helpers:
https://github.com/sendgrid/sendgrid-nodejs/blob/master/lib/helpers/mail/mail.js

Kitchen sink example
https://github.com/sendgrid/sendgrid-nodejs/blob/master/examples/helpers/mail/example.js

Blackbird is hiring

Are you a Full-Stack JavaScript developer who’s looking for your next challenge? Do you want to work on a modern stack, with amazing people, solving interesting problems? Drop me a line!