Express Email Handlebars

Collins Hillary
5 min readJul 15, 2020

Hello there, Welcome I will be showing you how to send emails using handlebars and Gmail for free while working on an Express Framework.

In any project, you will probably be needed to send emails to the application users in scenarios like password reset or user subscriptions.

There are services like SendGrid which you can pay to get email services and there is also Gmail which you can use to send this email which is not recommended because you will have to set off the security state of that account being used to send the emails. In either way, the method I will be showing you will cover all and allow dynamic changing of email settings in your applications.

So let’s get started. You will need a couple of things as we start.

Go to this link below and clone the repository that will act as our project skeleton

Once you have it cloned and understand how it flows. We can now continue to the project at hand.

We will have to make a few assumptions,

  1. I assume we will be using the MongoDB database
  2. I assume you know how to work and already have made necessary connections to the Mongo Database

Now install these modules below by running the following commands:-

  1. npm install nodemailer
  2. npm install nodemailer-express-handlebars

Those are the only modules we need!

Next, create a folder on the route folder called config. This folder will contain our email configuration. Create under this folder a file named email.js.

In our email.js file paste the following code:-

require(‘dotenv/config’); //load the dotenv config file

let nodemailer = require(‘nodemailer’);

exports.GmailTransport = nodemailer.createTransport({

service: ‘gmail’,

auth: {

user: process.env.GMAIL_USERNAME,

pass: process.env.GMAIL_PASSWORD

}

});

exports.ViewOptionresetemail = (transport, ejs) => {

transport.use(‘compile’, ejs({

viewEngine: {

extName: ‘.ejs’,

partialsDir: ‘emails/msgtemplates/’,

layoutsDir: ‘emails/msgtemplates/’,

defaultLayout: ‘resetemail.ejs’,

},

viewPath: ‘emails/msgtemplates/’,

extName: ‘.ejs’,

}));

}

email.js file

Just to explain some of the code.

a) The first line of code imports the variables stored in the environment configuration file.

b)We then require the nodemailer module that we use to create the transport function where we specify the service as Gmail and for auth, we pass our Gmail username and password.

c)We then create another function that will be used to point to the email template using handlebars. read more on that here.

If you are using SendGrid SMTP service and have the credentials you can replace our exports.GmailTransport with this:-

SendGrid API

We are almost done, we now have to write the business logic that will handle the user password reset request and send the user an email.

Inside the service folder open the service.js file and add this code. Require the config file we created and the handlebars module then create a function called passReset that we will pass the user email from the request body so that we can use it as the recipient email.

const MailConfig = require(‘../config/email’); //*load the Mail Config

const hbs = require(‘nodemailer-express-handlebars’) //*load email express handlebars

const gmailTransport = MailConfig.GmailTransport; //*initiate transport method

exports.passReset = async(email) => {

try {

//*get user

var user1 = await userPost.find({email:email})

//* client reset section

var randomstring = Math.random().toString(36).slice(-10);

Object.keys(user1).forEach(async function(key) {

var userrows = user1[key];

try {

//*send reset details via email

MailConfig.ViewOptionresetemail(gmailTransport,hbs);

let HelperOptions = {

from: ‘your email@gmail.com’,

to: userrows.email,

subject: ‘Account password reset’,

template: ‘resetemail’,

context: {

email:userrows.email,

token:randomstring

}

};

gmailTransport.sendMail(HelperOptions, (error,info) => {

if(error) {

throw new Error(error.message)

}

})

} catch (e) {

throw new Error(e.message)

}

});

} catch(e) {

throw new Error(e.message)

}

service.js

And that’s it. We have looked in the database for a user with that email that has been passed from the request, and when that user is found we loop through his/her details and get his emails and we use it as userrows.email as the recipient and we also pass it to the email template.

We have even created a random string that is generated and sent to the user. Now to Note: the line of code on number 545, that is where we define variables that you want to pass to the email. As you can see we are only passing the user email and the random token. You can pass anything you want.

We finally create the email template that will be seen by the user in his/her inbox.

Create a folder called emails then inside it create another folder called msgtemplates then inside it create a file called resetemail.ejs.

Inside resetemail.ejs you can style your email in whichever way you want it.

Mine looks something like the one below.

resetemail.ejs

To note: The variable we passed (the email and token), we show them on the template dynamically by enclosing them on {{}} as shown above.

That's it, guys. Your project structure should now look something like this.

project structure

Remember to put your email auth details in your .env file.

That’s it, hope everything was clear and now you can be able to use node handlebars to send dynamic emails in any node/express project. If not, don’t hesitate to reach out.

Author: Collins Munene

email: collinshillary1@gmail.com

--

--

Collins Hillary

Software and Immersive Tech Developer and Security Analyst