Email Templating with EJS (Node + Express + SendGrid)
Published: 2020-01-02 06:54:18

---

firstPublishedAt: 1577342561135
latestPublishedAt: 1577457222562
slug: email-templating-with-ejs-node-express-sendgrid
title: Email Templating with EJS (Node + Express + SendGrid)

---

#nodejs #express #ejs

![Photo by [Mockaroon](https://unsplash.com/@mockaroon?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/template?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)](https://cdn-images-1.medium.com/max/12032/1*MM2L7g1BEHa8ski3RCAM5A.jpeg)

I’ve been building a social links website [8link](https://www.8link.in/?ref=medium), which requires me to interact with my users at different levels. So 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)

1. Password reset link

1. Automated response to user queries

1. The actual response to User queries

1. 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](https://sendgrid.com/solutions/email-api/) to achieve this goal.

> SendGrid already has a Templating service, if you are interested you can check it [here](https://sendgrid.com/docs/ui/sending-email/how-to-send-an-email-with-dynamic-transactional-templates/).

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,

```
npm i --save express cors ejs
```

Our Package.json should look like:

![package.json file](https://cdn-images-1.medium.com/max/1792/1*4KnnrY1HX6LCh8S7djHtNw.png)

---

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

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

{% gist https://gist.github.com/far11ven/28dc098df4e3762f498f2c72741fec0c %}


it should give us the following response:

![/hello on localhost](https://cdn-images-1.medium.com/max/960/1*bX6CnP-NNwnBN1Rxuh6v2w.png)

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

![](https://cdn-images-1.medium.com/max/798/1*0dtPUAeab8tupUAwxjKfLg.png)

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

{% gist https://gist.github.com/far11ven/e161c86d32854892dcaccf946aeb77ec %}


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 = “John@example.com”;

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:

![](https://cdn-images-1.medium.com/max/3840/1*Y5Gtffdna1ZO_N3J-X62xQ.png)

**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](https://sendgrid.com/docs/API_Reference/api_v3.html) 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: “welcome@8link.in”, 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:

{% gist https://gist.github.com/far11ven/62ec9dcf0c0ed7147ca3f75b55275c21 %}

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

![](https://cdn-images-1.medium.com/max/1512/1*V4fQgNhZOtrM7FzSkOEcRQ.png)

Full Code on Github: [https://github.com/far11ven/SendGrid-Mailer](https://github.com/far11ven/SendGrid-Mailer)

**Original article on**: [https://blog.kushalbhalaik.xyz/email-templating-with-ejs-node-express-sendgrid/](https://blog.kushalbhalaik.xyz/email-templating-with-ejs-node-express-sendgrid/)