How to use Handlebars to send emails via SendGrid in a Node.js application

David Asaolu - Jul 4 '22 - - Dev Community

The ability to send email to users is one feature most modern web applications have. Whether you are sending a passcode to the user’s email address before they gain access to a resource or sending a confirmation email or newsletters to users, we tend to need this feature at some point when building web applications.

But without the right tool, sending emails to users can be a challenge which is one of the reasons SendGrid exists. SendGrid enables developers to add different email communication features to web applications painlessly within the shortest time possible.

SendGrid is a fast and scalable service that processes billions of emails monthly. With SendGrid, you can monitor every email you send via the dashboard provided. It is simple and easy to use.

In this tutorial, I will walk you through creating email templates using Handlebars and sending emails via SendGrid. We will first create an HTML template using Handlebars, and then connect the template to a Node.js server where we send the emails using SendGrid.

What is Handlebars?

Handlebars is a JavaScript templating engine that enables you to generate dynamic HTML pages effortlessly. Templating engines like Handlebars convert JavaScript functions into HTML templates and replace variables with actual data.

Node.js has several templating engines, such as EJS, Pug, Nunjucks, and doT but Handlebars stands out because it has a faster execution time and provides a simple syntax for adding dynamic content to your webpage using different layouts.

Why use Handlebars?

  • Simple to use
    Handlebars have a simple syntax making it easy for new users to understand. You do not need to run many configurations to use Handlebars in your web applications. Once you install it, you can start using the templating engine immediately.

  • Excellent documentation
    Handlebars have excellent documentation, making it easy for new and existing users to navigate and learn about its features rapidly.
    Handlebars documentation is short and developer-friendly, and you are less likely to run into bugs because it has detailed documentation.

  • Ability to create custom helpers
    Helpers are JavaScript functions registered by Handlebars to render different templates or HTML layouts. Handlebars allow you to extend the helpers library by creating reusable JavaScript functions for commonly used web layouts.

  • Faster execution time
    Compared to templating engines like Mustache, Handlebars has a faster execution time because it compiles the JavaScript functions into HTML templates once and then calls the compiled function for subsequent usage.

  • Good architectural design
    Handlebars is a simple templating engine with a structured layout making it easy for anyone to read and understand the codebase. Handlebars separate the views and logic into different folders, thus making it a logic-less templating engine.

Next, let’s create an email template using Handlebars on a Node.js server.

Create a Handlebars template in Node.js

  • Download and install Node.js from its website, if you don’t have Node.js installed on your computer.

  • Create a folder that will contain our app.

  • Open your terminal and navigate into the folder.

    cd <app–name>
Enter fullscreen mode Exit fullscreen mode
  • Create a package.json file by running the code below. Fill in all the required information.
npm init
Enter fullscreen mode Exit fullscreen mode
  • Create an index.js file - the entry point to the web application.
touch index.js
Enter fullscreen mode Exit fullscreen mode
  • Install Handlebars by running the code below.
npm install handlebars
Enter fullscreen mode Exit fullscreen mode
  • Create a templates folder containing the index.handlebars file.
mkdir templates
cd templates
touch index.handlebars
Enter fullscreen mode Exit fullscreen mode
  • Copy the following code into the index.handlebars file
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Message</title>
</head>
<body>
    <p>Hello {{name}}</p>
    <p>We just received your application and we are pleased to inform you that you are invited to the next stage of interview</p>
    <p>Your interviewer is {{interviewer}}</p>
    <p>Best regards,</p>
    <p>Sheggs Company</p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

The code snippet above is a Handlebars template that displays the content within the body tag.
Name and interviewer represent variables that store dynamic content retrieved from the compiled template.

Next, let’s learn how to replace these variables with exact values

  • Open the index.js file and import Handlebars.
//in index.js
const handlebars = require(“handlebars”)
Enter fullscreen mode Exit fullscreen mode
  • Import the file system module from Node.js. The file system module allows you to read and write files on your computer system.
const fs = require(“fs”)
Enter fullscreen mode Exit fullscreen mode
  • Create a reference to the Handlebars template. fs.readFileSync() enables us to read a file and return its content.
const emailTemplate = fs.readFileSync(path.join(__dirname, "/templates/index.handlebars"), "utf-8")
Enter fullscreen mode Exit fullscreen mode
  • Install path from Node.js. The path.join() method above creates an absolute URL to the file.
const path = require(“path”)
Enter fullscreen mode Exit fullscreen mode
  • Compile the Handlebars template, and provide the values for the name and interviewer variables.
const template = handlebars.compile(emailTemplate)

const messageBody = (template({
name: "David Islo", 
interviewer: "Scott Greenwich"
}))
Enter fullscreen mode Exit fullscreen mode
  • Try logging the messageBody variable to the console, you should retrieve the template’s HTML content.
    console.log(messageBody)
Enter fullscreen mode Exit fullscreen mode

Congratulations, the email template is completed. Next, let’s learn how we can send this template as an email.

How to send Emails using SendGrid

In this section, you will learn how to send emails using SendGrid.

Setting up SendGrid

  • Install SendGrid and Dotenv. Dotenv enables us to load data from environment variables into the Node.js web application. The environment variables store private keys, API keys, and passwords.
npm install dotenv @sendgrid/mail
Enter fullscreen mode Exit fullscreen mode
  • Create an empty .env file.
touch .env
Enter fullscreen mode Exit fullscreen mode
  • Visit SendGrid homepage to create an account.

  • Enable Two-factor authentication.

  • Select API Keys under Settings on the sidebar.

  • Create your API Key by selecting Mail Send under Restricted Access.

  • Copy and paste your API Key into the .env file.

SENDGRID_API_KEY=<SG.your_api_key>
Enter fullscreen mode Exit fullscreen mode
  • Adding SendGrid to a Node.js server
Import SendGrid and Dotenv in the index.js file.

const sgMail = require("@sendgrid/mail")
require("dotenv").config()
Enter fullscreen mode Exit fullscreen mode

Set SendGrid API key to that of the environment variable.

sgMail.setApiKey(process.env.SENDGRID_API_KEY)
Enter fullscreen mode Exit fullscreen mode

Copy the code below

const messageInfo = {
    to: "<email_recipient>", 
    from: "<registered_sendgrid_email>", 
    subject: "Congratulations! You are made it!", 
    html: messageBody //Handlebars template
}

//Pass the messageInfo object into SenGrid send function
sgMail.send(messageInfo, (error, result) => {
    error ? console.log("Email not sent!") : console.log("Email Sent!")
})
Enter fullscreen mode Exit fullscreen mode

From the code snippet above:

  • I created a messageInfo object that accepts all the needed email parameters from the function. The html key enables us to send HTML elements as a message to the recipient.
  • The sgMail.send() function sends the email to the recipient and returns a callback function if there is an error.

Conclusion

In this tutorial, you have learned how to create email templates using Handlebars and send emails using SendGrid in a Node.js application.

SendGrid makes it easy to integrate email communication into web applications at zero cost. Whether you are sending a single text or using a templating engine such as Handlebars, SendGrid can handle both tasks efficiently.

If you want to build a web application that enables you or users to send and receive emails, SendGrid is an excellent choice.

Thank you for reading!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .