Published on

How to Send MJML Templates with Node and SendGrid

Authors

I have been using MJML to create various email templates for what I am working on.

MJML is great as it cuts down a tonne of complexity vs working out what archaic CSS and HTML you can use to make sure it is still compatible in different mail clients.

The one thing I could not get to work properly was sending mails using the MJML app with an API key. I kept running into issues with the API I could not resolve.

Luckily I found this blog post that explains how to do this using NodeJS and PostMark.

I followed most of this although I ran into issues when using the MJML npm package - it would simply not resolve paths to mj-includes no matter what I did to the path config in the options object.

I found a fairly straightforward workaround - use the MJML cli. I found that this resolves paths correctly. So I added it to my dependencies: yarn add mjml-cli and adapted the original blog post to use the cli and SendGrid (instead of PostMark as it has a nice free tier which is useful for testing). My final code was:

require('dotenv').config()
const fs = require('fs')
const sgMail = require('@sendgrid/mail')
const { execSync } = require('child_process')

const sgAPIKey = process.env.SENDGRID_API_KEY
sgMail.setApiKey(sgAPIKey)

const folderPath = `${__dirname}/../email/example`
const generalTemplateFilePath = `${folderPath}/general-template.mjml`
const welcomeTemplateFilePath = `${folderPath}/welcome-template.mjml`
const generalTemplate = fs.readFileSync(generalTemplateFilePath)
const welcomeTemplate = fs.readFileSync(welcomeTemplateFilePath)

const getMjmlAsHtml = (pathToMJML) => {
  return execSync(`mjml ${pathToMJML}`).toString()
}

const sendMessage = (htmlMessage, subject = 'Test SendGrid Email') => {
  console.log('----------------------------Sending message...')
  const msg = {
    to: '[email protected]',
    from: '[email protected]',
    subject: subject,
    html: htmlMessage,
  }

  console.log('message')
  console.log(msg)
  sgMail.send(msg)
  console.log('----------------------------Sent')
}

const asHtml = getMjmlAsHtml(welcomeTemplateFilePath)

console.log(asHtml)

sendMessage(asHtml, 'Test - Welcome Template Example')

In the above you will need to change your from to an address you have verified. to can be changed to whatever address you want to send to.

Note: be sure to check your spam folder as mine all ended up there despite setting up the verified address with a valid postal address.

Sources used to build up the above: