How to Send SMTP Emails in Node.js With SendGrid

March 11, 2022
Written by
Reviewed by

When it comes to email services in application development, a hosted email API – such as Twilio SendGrid – is the way to go as it offers ways to customize the setup to your needs. However, you may want to send emails through SMTP (Simple Mail Transfer Protocol) if it is already on your existing platform and since it is an email standard that's used universally.  Luckily, Twilio SendGrid offers an SMTP Relay service without having to set up your own server. You’ll also still have access to in-depth metrics, analytics tracking, increased deliverability rates and even more SendGrid features through the X-SMTPAPI header.

In this tutorial, you’ll learn how to send out emails through Twilio SendGrid’s SMTP Relay in Node.js.

If you have the option and are still deciding whether to integrate SendGrid through our API or SMTP Relay, we highly recommend using our Web API. SMTP requires more back and forth conversation between your server and the client; because of this you may experience more latency, and multiple points of failure. For more information on this, check out this SendGrid blog: Web API or SMTP Relay: How Should You Send Your Email?

Not only is our Web API faster and more flexible, you’ll have access to all of our services including email templates, email validation, and marketing tools as opposed to just sending emails. To see what else you can do with the SendGrid API, check out our API Reference.

If you are looking to switch or get started with sending emails in Node.js with the SendGrid API, check out How to Send Emails in JavaScript/Node.js with SendGrid.

Prerequisites

Configure SendGrid

To get started, you’ll need to do two things with SendGrid: Verify your Sender Identity, and generate your API key.

Verify your Sender Identity

SendGrid customers are required to verify their Sender Identity to ensure that they own the email address that they’ll be using. A Sender Identity represents your 'From' email address—the address your recipients see as the sender of your emails.

It's recommended to complete Domain Authentication to verify your Sender Identity, but to speed things up for this tutorial, you’ll be completing Single Sender Verification which is used for testing purposes.

Log on to SendGrid and head over to the settings tab on the left-hand side. Click on the dropdown and click on Sender Authentication.

Settings tab on SendGrid dashboard with the Sender Authentication link highlighted

Within the Sender Identity section click on the Verify a Single Sender button and fill out the form that pops up with your information.

Single Sender Authentication Form

Once the form is filled, click on the blue Create button and you’ll receive an email in your inbox to verify your email address. Open that email and click on Verify Single Sender which will redirect you back to SendGrid to let you know that your email is ready to be used.

Generate your API key

On your SendGrid dashboard, head to the API Keys section by heading to the settings tab on the left-hand side and clicking API Keys.

  

Settings tab on SendGrid dashboard with the API Keys link highlighted

Click the blue “Create API Key” button on the top right and a form will appear.

Create an API key form

Choose whatever name you’d like for your API key and click the blue Create & View button. Copy your API key and store it in a safe place.

Build your Node.js Application

Now that you have verified your email address and have gotten your API key with SendGrid, let's start building out the application.

In your terminal or command prompt, navigate to your preferred directory and enter the following commands to create your project:

mkdir smtp-emails
cd smtp-emails
npm init -y

This command will create your project file and scaffold out your Node project by creating a package.json file that will contain your project's metadata and package dependencies.

Next, you’ll need to install two dependencies: dotenv and Nodemailer. dotenv will be used to store environment variables and Nodemailer – the most popular Node.js email package – will be used to send emails through SMTP. Enter the following command in your terminal to install these dependencies:

npm i dotenv nodemailer

To store your SendGrid API key, create a file in the same directory named .env and place the following in it, while replacing the XXXXXX placeholders with your actual API key:

SENDGRID_API_KEY=XXXXXX

Now create a file called index.js in the same directory and add the following code to it:

require('dotenv').config();
const nodemailer = require("nodemailer");

let transporter = nodemailer.createTransport({
   host: 'smtp.sendgrid.net',
   port: 587,
   auth: {
       user: "apikey",
       pass: process.env.SENDGRID_API_KEY
   }
})

This code will initialize nodemailer and import environment variables from the .env file. It will then create a transporter with a given server host, port number, and authentication data.

SendGrid’s server host for SMTP relay is smtp.sendgrid.net and the recommended port to use is 587.

Port 587 is meant for an unencrypted or a TLS connection. If you need to use another port or are unsure which port to use check this out.

For the authentication data, you will need to provide a username and password. For connecting with SendGrids SMTP server, the username will be “apikey” and the password will be your actual API key. SendGrid will use the given API key to connect with your SendGrid account where you’ll be able to track and view sent emails.

Add the following code below the transporter:

transporter.sendMail({
   from: "SENDER_EMAIL", // verified sender email
   to: "RECIPIENT_EMAIL", // recipient email
   subject: "Test message subject", // Subject line
   text: "Hello world!", // plain text body
   html: "<b>Hello world!</b>", // html body
 }, function(error, info){
   if (error) {
     console.log(error);
   } else {
     console.log('Email sent: ' + info.response);
   }
 });

This last code chunk uses the transporter to send out an email with a given message configuration. It will then log the result of the email being sent.

X-SMTPAPI header

You can also pass in headers to the ”header” property to the message configuration. SendGrid’s SMTP service also allows you to pass SendGrid a JSON string with as many SMTP objects as you want through a header named X-SMTPAPI. Through this header, you can integrate SendGrid features – such as filters, scheduled sends, substitution tags and more – to your SMTP emails. For more information on this, check out Building an X-SMTPAPI Header on the SendGrid docs and SendGrid’s Node.js SMTPAPI helper library.

Send an email through SMTP

Before running the code don’t forget to change the SENDER_EMAIL and RECIPIENT_EMAIL placeholders with their respective email addresses.

Lastly, save the file, head back to your terminal and run the following command:

node index.js

You should see your console log that the email has been sent with the SMTP response code being 250. This means that the email has been successfully sent and delivered to the recipient.

Check the inbox of the recipient’s email and you’ll see the email that you sent through your code.

Next Steps

Nice! You’ve just successfully sent an email through SMTP using Node.js. Using SendGrid’s SMTP relay makes it easy for you to switch your existing SMTP server to SendGrid’s server without losing out on SendGrid functionality.

Going forward, you can even enable dedicated IP pools, suppression groups, and scheduled sends all through the X-SMTPAPI header with SendGrid. Happy building!

Dhruv Patel is a Developer on Twilio’s Developer Voices team. You can find Dhruv working in a coffee shop with a glass of cold brew or he can either be reached at dhrpatel [at] twilio.com or LinkedIn.