How to Implement SendGrid using Node.js
How to Implement SendGrid using Node.js

How to Implement SendGrid using Node.js

Spread the love
Sendgrid implementation using Node.js
Sendgrid v3 send email using node.js

Sendgrid is one of the most popular email services used by the IT industry, for marketing as well as transactional emails. You can simply send welcome emails, password reset emails, communication updates, etc via SendGrid or even new product feature updates. So in today’s post, I’ll show you how to create a free account on SendGrid & integrate it with your Node.js code to automate the process. So let’s begin.

Step 1: Sendgrid Account Creation

  1. Go to https://sendgrid.com/ and register for a free account.
SendGrid dashboard
SendGrid dashboard

2. Go to settings->API keys to generate the API key which will be used by the node code to send the email (Store the API key at a safe place).

3. Now go to Email API->Dynamic Templates to create the template to send an email. Then create the version. Sendgrid allows creating multiple versions & any single version to be active. You can choose the SendGrid template or create the custom template as you like.

One can send a static email or personalize the email based on your requirement. For personalizing email, SendGrid uses the Handlebars. you can read about handlebars here.

SendGrid dynamic template
SendGrid dynamic template

As shown in the above image, you can pass dynamic data through {{}} with variable name inside {{variableName}}. For example: {{firstName}}.

You can test your email by putting test data on the test data tab in JSON format. For example: {“firstName”: “Shraddha”}.

testing of SendGrid template
testing of SendGrid template

Step 2: Node.js Setup

1. Install Axios using npm.

npm install --save axios

2. Create an email helper file in your node project. Inside the email helper file paste your SendGrid API key & endpoint of SendGrid send API. I have created an ‘EmailType’ object to store multiple dynamic template id.

const axios = require('axios');
const sendgridApiKey = 'SG..................................';
const emailSendUrl = 'https://api.sendgrid.com/v3/mail/send';
const EmailType = {
 WELCOME_EMAIL: 'd-026a2f461bdd480098be08a2cb949eea',
 CHANGE_PASSWORD: 'd-026a2f4hsyw20098be08a2cb949eea',
 OTP: 'd-026a2f461bdd480098be08bxhsyeyyy',
}

Now to send the data, you can create a function that you can export & use in another file to send the email data. Template Id, Personalizations & from information is compulsory data to be sent to SendGrid. You can send attachments, BCC, CC, Reply to, and many more fields based on the requirement. Below is the email helper that contains all the necessary data.

module.exports.sendTemplateEmail = (fromEmail, toEmail, replyTo, fromName, template, substitutions, attachment) => {
if (!EmailType[template]) {
  return Promise.reject(new Error('Template not defined'))
} 
const email = {
 from: {
  email: fromEmail,
  name: fromName,
 },
template_id: EmailType[template],
personalizations: [{
  to: [{
   email: toEmail,
  }],
  dynamic_template_data: substitutions,
 }],
};
if (attachment) {
 email.attachments = attachment
}
if (replyTo) {
 email.reply_to = {
  email: replyTo,
  name: 'Reply',
 }
}
return axios({
  method: 'post',
  url: emailSendUrl,
  headers: {
   Authorization: `Bearer ${sendgridApiKey}`,
  },
  data: email,
});
}
Sample email-helper.js file to send data
Sample email-helper.js file to send data

3. Now to call the sendTemplateEmail function let’s create an index.js file. Import the email helper file. Let’s create the welcome API and then send the data to the sendTemplateEmail function with the necessary data. And there you go! On successful signup, the user will receive the welcome email with a personalized name & verification link.

Sendgrid implementation using Node.js API to send data
Index.js file to send data

To see if the code works, call the API by sending sample data with the postman.

And that’s it. Hope you found this article helpful. Thank you.

One comment

  1. Pingback: Handlebars: Partials, Helpers & much more | Noob2Geek

Leave a Reply

Your email address will not be published. Required fields are marked *