How to send email using SendGrid in NodeJS/JavaScript?

SendGrid is a great alternative to send emails in JavaScript / NodeJS. Setup of SendGrid in node js project is kinda very simple.┬áLet’s send email using SendGrid.

Node js is all prerequisite for SendGrid to begin with. Let’s assume you have a NodeJS and you want to integrate your project with SendGrid to send emails.

Sendgrid have an npm package @sendgrid/mail, install this package in your project by running following command.

npm install --save @sendgrid/mail

Once this npm package is installed, go to your file from where you want to send the emails.

Before you write any code one more thing is required and that is the API key. You can easily get an API key by logging in to the SendGrid website and creating a new API key.

Now the code parts begin. All you have to do is write a few lines of code according to SendGrid documentation,

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(SENDGRID_API_KEY);

// your email here

const msg = {
 to: 'test@example.com',
 from: 'test@example.com',
 subject: 'Sending with SendGrid is Fun',
 text: 'and easy to do anywhere, even with Node.js',
 html: 'and easy to do anywhere, even with Node.js',
};

// this will send the email

sgMail.send(msg);

and that’s all.

Leave a Reply

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