An email template is an  reusable HTML file that is used to build email campaigns. It allows us to add things like images and links to an email and, along with CSS-lets us style the campaign to better reflect our company or personal styles. They’re normally saved in your email service provider (ESP) or in something like Litmus Builder, and provide a base on which to add copy, images, and links specific to that email campaign.

Handlebars is a simple templating engine. Handlebars provides a simple, powerful way to include dynamic content, directly within email templates. Handlebars syntax allows all of this dynamic templating to occur outside of code, meaning changes are done quickly in the template, with no update to a code base required.

Install handlebars

npm install handlebars

Create handlebars template file i.e .hbs/.html file

    <title>HTML Title</title>
    	<p>Hi {{name}},</p>

you can also add image, link, videos and css to the template file.

now we create a .js file where our code will reside.

const nodemailer = require("nodemailer")
const mg = require("nodemailer-mailgun-transport")
const handlebars = require("handlebars")
const fs = require("fs")
const path = require("path")
const emailTemplateSource = fs.readFileSync(path.join(__dirname, "/template.hbs"), "utf8")
const mailgunAuth = {
  auth: {
    api_key: "key-12341234123412341234",
    domain: "One of your domain names listed at your"
const smtpTransport = nodemailer.createTransport(mg(mailgunAuth))
const template = handlebars.compile(emailTemplateSource)
const htmlToSend = template({name:"xyz"})
const mailOptions = {
  from: "",
  to: "recipient@domain",
  subject: "EMAIL SUBJECT LINE",
  html: htmlToSend
smtpTransport.sendMail(mailOptions, function(error, response) {
  if (error) {
  } else {
    console.log("Successfully sent email.")

First of all we include "mailgun-js" and "handlebars" npm packages. And also we include  "path" and "fs" node.js modules to read the file.

Now we import template.hbs file and store it in emailTemplateSource variable.

And then we create mailgunAuth object for authorization that store api_key and domain.

Then we created a SMTP Transprot for Nodemailer using the mailgunAuth object we created.

Now, we created template and htmlToSend variable to construct the HTML that make up the body of the email. Here we pass message value to template.hbs file.

And the last thing we did before sending the email is to create a variable data, which contains from, to, subject and htmlToSend fields.

Finally, the "sendMail()" method will send the email.