Integrate Sendgrid email service using NodeJS

Sendgrid
Reading Time: 3 minutes

SendGrid is a platform that offers email services and provides libraries to help you quickly and easily integrate with the Web API in 7 different languages: C#GoJavaNode JSPHPPython, and Ruby. In this blog, we are going to discuss how to integrate Sendgrid email services by using Node JS.

To integrate Sendgrid with Node JS application we need to install latest version of node. Following are the steps to integrate sendgrid services with NodeJS:

STEP 1: Setup a Node JS application with Express

Firstly, we need to create Node JS application by using follow commands:

mkdir sendgrid-app // Create a new directory
cd sendgrid-app // Change current path to project directory

Now project needs to be initialised and link it with NPM. NPM is already installed with Node JS setup.

npm init

This creates a package.json file in sendgrid-app folder. The file contains references for all npm packages you have downloaded to your project. Now install express in this project by using follow command.

npm install express --save

This command installs the express in our application and save the dependency to dependecies list inside package.json file. Now create a new file named app.js with the following code:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Listening on port 3000!');
});

Now application is ready to integrate with sendgrid.

STEP 2: Setup on Sendgrid

Just signup on Sendgrid and get your API keys to integrate with Node JS application. The API keys are available in Settings -> API keys. Just create a new API key by clicking on Create API key button. You will receive an API key and keep it at some secure place. The reference for API key is attached:

Sendgrid API key
STEP 3: Integrate sendgrid with Node JS application

After getting API keys, install sendgrid dependency by using following command:

npm install @sendgrid/mail --save

This command adds the sendgrid dependency to package.json. Now we are ready to code for mail services in our application.

STEP 4: Node JS Code

Firstly we need to connect our Node application with our Sendgrid account using API key by following commands:

const sendgridMail = require('@sendgrid/mail');

sendgridMail.setApikey('SENDGRID_API_KEY');

These commands connect our application with SendGrid. Now we have two methods to create email templates:

  1. Using Dynamic Templates
  2. Using Custom HTML code
1. Using Dynamic Templates

To create dynamic email templates we just need to add template id in our code. Template id is provided with the form details as follow:

Sendgrid Template ID

Just copy the template ID and paste inside the code as follow:

templates = { 
     sample: 'd-ba9873e1a396416294c9f3706564f7f5'
}

Now just create a function to send an email by passing the template ID as follows:

function sendEmailWithDynamicTemplate(data) {
    const msg = {
        to: data.receiver,
        from: data.sender,
        templateId: templates['sample'],
        dynamic_template_data: {
            email: 'test@gmail.com'
        }
    }

    sendgridMail.send(msg, (error, _) => {
        if (error) {
            return error;
        } else {
            return 'Success message';
        }
    }
}

In the above code, dynamic_template_data key is used to pass the data to render dynamically on the form. Also in the form just mention {{{ email }}} variable where you want to render the dynamic data field as follow:

Sendgrid Dynamic template
2. Using Custom HTML code

If we want to create an email template by our own custom HTML then we have to pass the following data to sendgridMail.send():

const email = "test@gmail.com";
const htmlData = "<div>Hi " + email + "</div>";

const msg = {
    to: data.receiver,
    from: data.sender,
    subject: 'Sample Mail',
    html: htmlData
}

To test the code just run the following command:

node app.js

That’s all about the integration of SendGrid email service with node application. If you want to explore more on SendGrid API details, please visit: SendGrid API Docs

Knoldus Footer

Written by 

Rudar Daman Singla is the Trainee Software Consultant at Knoldus Software LLP. He has done B.Tech. from Jaypee University of Information technology, Waknaghat(Solan). He has good knowledge of languages C, C++, Java, Scala, HTML, CSS, PHP, Node and Angular. He is also interested in VFX. As a fresher, he always tries to explore the different type of software and tools.