I’ve built a lot of applications to demonstrate what SendGrid can do over the past few years. Recently, I’ve started either updating them, getting rid of really old ones, or replacing them with newer ideas and more modernised examples.

With the apps I’ve been updating, the biggest change has been removing all of the inline template code for the emails being generated by the app and moving it to SendGrid’s Template Engine, leaving behind a much cleaner looking codebase and a much more manageable set of templates.

Migrating a simple app to Template Engine is really easy, here’s how I did one of mine:

Migrating “Oh, Cardless” to Template Engine

I built Oh, Cardless to fix the problem of either forgetting or running out of business cards. You can read more about what it does and how I built it in the post Oh, Cardless: My Business Card Email App from last year.

Here’s the main function I use to send out the cards:

Massive, isn’t it? Thankfully, there’s a lot that can now be removed from this to clean it up.

We’re going to take away:

  • The text_block variable (Template Engine handles plain text email too!)
  • The html_block variable
  • The filter that adds the footer to the bottom of the email

Making the New Template

A simple copy and paste is really all it takes. In this instance it took about 5 minutes to get everything ready. I recorded and annotated the process–you can see it below (500% faster):

Integrating Template Engine

Now that all our template code has been removed, let’s look at how the code above has changed:

Much cleaner. You’ll notice that although the template code is gone, some new elements have been added:


cardEmail.setFilters({"templates": {"settings": {"enabled": 1, "template_id": "325ae5e7-69dd-4b95-b003-b0109f759cfa"}}});
cardEmail.addSubstitution('-from_name-', process.env.FROM_NAME);
cardEmail.addSubstitution('-twitter-', process.env.TWITTER);
cardEmail.addSubstitution('-from_address-', process.env.FROM_ADDRESS);
cardEmail.addSubstitution('-sign_off-', process.env.SIGN_OFF);
cardEmail.addSubstitution('-signature-', process.env.SIGNATURE);
cardEmail.addSubstitution('-card_image_url-', process.env.CARD_IMAGE_URL);

These are the substitutions required by the template you see being built in the video above. I’ve passed them in one at a time because it looks more readable, but it’s also possible to pass all of them together.

That’s it, overall it’s a relatively quick process that gives you much cleaner, manageable emails that you can tweak and play around with without having to redeploy any code to production.



Martyn Davies is a Developer Evangelist at SendGrid and a creative developer based in London. He has worked in technology for over 14 years with a background in both the music industry and technology. A serial hackathon organiser, mentor and startup advisor, you’ll find him presenting, demoing, hacking and chatting at hack days, conferences and meetups in the UK & Europe on a regular basis.