Email Templating with EJS (Node + Express + SendGrid)
#ejs #node-js #express-js

Email Templating with EJS (Node + Express + SendGrid)

18 January, 2020

3 min read

I’ve been building a social links website 8link, which requires me to interact with my users at different levels. So based on the type of email interaction with my users, I’ve narrowed it down to the following categories of emails:

  1. Welcome email (With verify link)
  2. Password reset link
  3. Automated response to user queries
  4. The actual response to User queries
  5. Occasional promo or newsletters

I’ve been using a Node.js +Express back-end and I wanted to achieve it with same frame-work. So I started using SendGrid Email API to achieve this goal.

SendGrid already has a Templating service, if you are interested you can check it here.

Back to Templating with EJS, in This article, we’ll see how can we create Re-Usable HTML Templates with EJS and then deliver them with SendGrid.

We’ll start by creating a simple node project:

npm init sendgrid-mailer

Install following dependencies,

Our Package.json should look like:

npm i --save express cors ejs
package.json file
Package.json at this point

Let’s create a simple endpoint to serve our email “/hello”

Notice //set express view engine to ejs
app.set(“view engine”, “ejs”);

it should give us the following response:

/hello on localhost

We are halfway there, Now create a welcome-mail.ejs file in views (Template) folder in the project root directory.

Now add some HTML code in there, which will serve as an underlying template for our welcome mail:

You will see the following syntax in this HTML, which is used to receive data before rendering it. We are using the following variables for manipulating data:

//these are EJS expressions to dynamically receive and display data while rendering an HTML

<%= user_firstname %>
<%= confirm_link %>

Now we need to make changes to our “/hello” endpoint

We’ll need to import following to our index.js file:

//imports
const path = require(“path”);
const ejs = require(“ejs”);

and our “/hello” app route function will change to :

app.get(“/hello”, (*req*, *res*, *next*) => {
let emailTemplate;
let capitalizedFirstName = “John”;
let userEmail = “[email protected]”;

ejs
.renderFile(path.join(__dirname, “views/welcome-mail.ejs”),
{
  user_firstname: capitalizedFirstName,
  confirm_link: “http://www.8link.in/confirm=" + userEmail
})
.then(*result* => {
  emailTemplate = result;
  res.send(emailTemplate);
})
.catch(*err* => {
  res.status(400).json({
      message: “Error Rendering emailTemplate”,
      error: err
     });
  });

});

in here, ejs.renderFile() take .ejs file path and specify values for user_firstname and confirm_link

Now if we hit “/hello” we get:

Whoops.. we now have our welcome template, we just have to deliver it via email now.


Let's integrate SendGrid now:

First signup for SendGrid mail API, by clicking here and get the API -KEY

Now get @sendgrid/mail package from npm.

npm i --save @sendgrid/mail

Import following into index.js

const SGmail = require(“@sendgrid/mail”);

Now in our code first register the SendGrid API Key

SGmail.setApiKey(process.env.SendGrid_Key);

//Note: store SendGrid_Key in your projects' config file

and replace res.send(emailTemplate); with following code:

const message = {
  to: userEmail,
  from: { email: “[email protected]”, name: “8link” },
  subject: “Welcome link”,
  html: emailTemplate
};

return SGmail.send(message).then(*sent* => {

// Awesome Logic to check if mail was sent

   res.status(200).json({
      message: “Welcome mail was sent”

      });

}).catch(*err* => {

      console.log(“Error sending mail”, err);
      res.status(400).json({
          message: “Welcome mail was not sent”,
          error: err
      });

});

Our final code should look like:

And if I hit my “/hello” endpoint again, I should see that mail was sent successfully:

Full Code on Github: https://github.com/far11ven/SendGrid-Mailer

Original article on: https://blog.kushalbhalaik.xyz/email-templating-with-ejs-node-express-sendgrid