Sending e-mails in Node.js with templates

For the purpose of this tutorial, we will be using nodemailer, handlebars, and nodemailer-handlebars packages to handle the email sending functionality.

Nodemailer is a tool that uses an SMTP server, handlebars help us inject values into our Html templates and nodemailer-handlebars will compile our parts templates. We will focus more on handlebars templating.

Install the above requirements with npm i nodemailer handlebars nodemailer-handlebars.

My project folder structure currently looks like this

Project structure

Inside the views folder, we have the layouts folder which will contain the layout of our templates. The partials folder will contain parts of the general layouts such as header, footer e.t.c while the final templates will sit in the views folder directly. All our server code will be in the index.js file.


We will convert the simple sample template above into a layout and partial handlebars files.

My project with the templates look like this

Updated project

footer.hbs partial file


layout.hbs layout file


The partial files are included using the double curly braces with their name e.g {{> footer}} and the three braces with the name “body” will hold injected values from a template that will inherit from the layout.

template1.hbs template file


The layout will be extended as shown in the picture above and the variable “name” will be injected as we’ll see soon.

The index.js above has all our server code and the email configuration. The SMTP credentials can be gotten from any SMTP provider, you can use GMAIL to test things out. We provide the paths to our templates and other configurations in the options object to be used by the nodemailer-handlebars package.

In the mailOptions object, the template to be used is indicated by the filename without extension. The context will hold all values to the variables used in the provided template.

Firing up the server and making two HTTP calls: localhost:3000/first and localhost:3000/second, we get two different emails delivered to the recipient's email address.


Software Engineer | Explorer.