Using SendGrid with Node

A good email service to use to send mail in your Node project is SendGrid. Using SendGrid with Node is very simple: you just need a SendGrid account and you’re ready to start.

If you do not have an account, you can sign up to a free 30 day trial of SendGrid on their Pricing and Plans page.

Not only will you be allowed to send a few thousand emails with the trial, there is also a useful npm module that will allow you to send mail using the SendGrid Web API V3 using Node.js.

To install the module, cd into your Node project and run the following command.

$ npm install sendgrid

You’ll now be able to include the mail helper class within your project.

var helper = require('sendgrid').mail;

Like other email libraries, you will need to configure fields such as the ‘from email’, ‘to email’, ‘subject’ and ‘content’.

// Define the 'from' email
var fromEmail = new helper.Email('from@example.com');
// Define the 'to email'
var toEmail = new helper.Email('to@example.com');
// Define a 'subject'
var subject = 'Hey! A subject.';
// Define the email body content
var content = new helper.Content('text/plain', 'Hello World! We've just sent an email.');
var mail = new helper.Mail(fromEmail, subject, toEmail, content);

Finally, define a variable, such assg to include the sendgrid module along with the SendGrid API key.

This API key is generated within your SendGrid account within the Settings -> API Keys section.

Using SendGrid with Node

In this section, create an API key and copy and paste it within your project.

var sg = require('sendgrid')('YOUR API KEY HERE');
var request = sg.emptyRequest({
  method: 'POST',
  path: '/v3/mail/send',
  body: mail.toJSON()
});
 
sg.API(request, function (error, response) {
  if (error) {
    console.log('Error response received');
  }
  console.log(response.statusCode);
});

The console.log(response.statusCode) line will output the status code of the email sending.

Any status code that begin with ‘2’, such as 200 or 202, indicate successful requests. For more information on the different status code, view the following page: https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html