Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Email API Quickstart for Node.js


In this quickstart, you'll learn how to send your first email using the Twilio SendGrid Mail Send API and Node.js(link takes you to an external page).


Prerequisites

prerequisites page anchor

Be sure to perform the following prerequisites to complete this tutorial. You can skip ahead if you've already completed these tasks.

  1. Sign up for a SendGrid account.
  2. Enable Two-factor authentication.
  3. Create and store a SendGrid API Key with Mail Send > Full Access permissions.
  4. Complete Domain Authentication.
  5. Install Node.js.

Skip the prerequisites

Sign up for a SendGrid account

sign-up-for-a-sendgrid-account page anchor

When you sign up for a free SendGrid account(link takes you to an external page), you'll be able to send 100 emails per day forever. For more account options, see our pricing page(link takes you to an external page).

Enable Two-factor authentication

enable-two-factor-authentication page anchor

Twilio SendGrid requires customers to enable Two-factor authentication (2FA). You can enable 2FA with SMS or by using the Authy(link takes you to an external page) app. See the 2FA section of our authentication documentation for instructions.

Create and store a SendGrid API key

create-and-store-a-sendgrid-api-key page anchor

Unlike a username and password — credentials that allow access to your full account — an API key is authorized to perform a limited scope of actions. If your API key is compromised, you can also cycle it (delete and create another) without changing your other account credentials.

Visit our API Key documentation for instructions on creating an API key and storing an API key in an environment variable. To complete this tutorial, you can create a Restricted Access API key with Mail Send > Full Access permissions only, which will allow you to send email and schedule emails to be sent later. You can edit the permissions assigned to an API key later to work with additional services.

Once your API key is assigned to an environment variable — this quickstart uses SENDGRID_API_KEY — you can proceed to the next step.


_10
export SENDGRID_API_KEY=<Your API Key>

Verify your Sender Identity

verify-your-sender-identity page anchor

To ensure our customers maintain the best possible sender reputations and to uphold legitimate sending behavior, we require customers to verify their Sender Identities by completing Domain Authentication. A Sender Identity represents your 'From' email address—the address your recipients see as the sender of your emails.

(information)

Info

To get started quickly, you may be able to skip Domain Authentication and begin by completing Single Sender Verification. Single Sender Verification is recommended for testing only. Some email providers have DMARC policies that restrict email from being delivered using their domains. For the best experience, please complete Domain Authentication. Domain Authentication is also required to upgrade from a free account.

Before installing Node.js, you can see if you already have a version on your machine.

(information)

Info

The Twilio SendGrid Node.js helper library supports the current LTS version of Node.js and versions 6, 7, 8, and 10.

Node.js version check

nodejs-version-check page anchor

Check your Node.js version by opening your terminal (also known as a command line or console) and typing the following command:


_10
node --version

If you have Node.js installed, the terminal should print something like the following output:


_10
v12.16.1

Though the SendGrid helper library supports Node.js back to version 6, we recommend using the latest version. Node.js version 12.16.1 was used to build this quickstart.

If you do not already have a version of Node.js installed, visit the Node.js website(link takes you to an external page) for instructions on downloading and installing a version appropriate for your operating system. The npm package manager also has a helpful installation guide(link takes you to an external page).


Starting the project

starting-project page anchor

Using a Twilio SendGrid helper library(link takes you to an external page) is the fastest way to deliver your first email with Node.js.

Start by creating a project folder for this app. You can name the project anything you like. We use sgQuickstart in the following examples.


_10
mkdir sgQuickstart

Next, navigate into the sgQuickstart directory where you will complete the rest of the tutorial.


_10
cd sgQuickstart

The npm(link takes you to an external page) package manager was included when you installed Node.js. You can use npm to install the Twilio SendGrid helper library as a project dependency. If you want to verify that npm is installed, you can type the following into the terminal.


_10
npm --version

The terminal should print something like the following output.


_10
6.13.4

(information)

Info

You can install the helper library using yarn(link takes you to an external page) if you prefer.

Before installing the package, you should first initialize your project with the following command.


_10
npm init

This command will print a chain of questions that help you create a package.json file. The package.json file stores a list of project dependencies. You can hit Enter or Return to skip any of the questions and use the default values.

Once you complete the initialization process, your package.json will contain a “main” property. This property stores the application entry point, which is "index.js". The application entry point is the main file Node.js will look for when running your application code. This will be important later. You can use any file name you want, but we'll use the default "index.js" in this quickstart.

Install the helper library

install-the-helper-library page anchor

To install the Twilio SendGrid helper library, type the following command into the terminal.


_10
npm install --save @sendgrid/mail

The terminal should print something like.


_10
$npm install --save @sendgrid/mail
_10
+ @sendgrid/mail@7.2.1
_10
added 15 packages from 19 contributors and audited 15 packages in 1.625s
_10
found 0 vulnerabilities

(information)

Info

If you see errors printed above the message, they are likely related to missing information in your package.json file. You can ignore these errors for this quickstart.


How to use Node.js to send an API email

how-to-use-nodejs-to-send-an-api-email page anchor

You're now ready to write some code and send your first email with Node.js. First, create a file in your project directory. Again, you can use index.js because that's the name of the "main" entry point file in the package.json file.

The following Node.js block contains all the code needed to successfully deliver a message with the SendGrid Mail Send API. You can copy this code, modify the to and from fields, and run the code if you like. We'll break down each piece of this code in the following sections.


_20
const sgMail = require('@sendgrid/mail')
_20
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
_20
_20
const msg = {
_20
to: 'test@example.com', // Change to your recipient
_20
from: 'test@example.com', // Change to your verified sender
_20
subject: 'Sending with SendGrid is Fun',
_20
text: 'and easy to do anywhere, even with Node.js',
_20
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
_20
}
_20
_20
sgMail
_20
.send(msg)
_20
.then((response) => {
_20
console.log(response[0].statusCode)
_20
console.log(response[0].headers)
_20
})
_20
.catch((error) => {
_20
console.error(error)
_20
})

Your API call must have the following components:

  • A host (the host for Web API v3 requests is always https://api.sendgrid.com/v3/ )
  • An API key passed in an Authorization Header
  • A request (when submitting data to a resource via POST or PUT , you must submit your request body in JSON format)

In your index.js file, require the Node.js helper library. The library will handle setting the Host, https://api.sendgrid.com/v3/, for you.


_10
const sgMail = require('@sendgrid/mail')

Next, use the API key you set up earlier. Remember, the API key is stored in an environment variable, so you can use the process.env() method to access and assign it using the helper library's setApiKey() method. The helper library will pass your key to the API in an Authorization header using Bearer token authentication.


_10
sgMail.setApiKey(process.env.SENDGRID_API_KEY)

Now you're ready to set up your "to", "from", "subject", and message body "text". These values are passed to the API in a "personalizations" object when using the v3 Mail Send API. The helper library allows you to store all this data in a single flat JavaScript object. Assign the object to a variable named msg.

Change the “to” value to a valid email address you can access. This is where your message will be delivered. Change the “from” value to the address you verified during the Sender Identity set up.

The "subject" can be any text. The email body can be either plain text or HTML. The helper library allows you to specify the type of email body by using either the "text" or "html" properties.


_10
const msg = {
_10
to: 'test@example.com', // Change to your recipient
_10
from: 'test@example.com', // Change to your verified sender
_10
subject: 'Sending with SendGrid is Fun',
_10
text: 'and easy to do anywhere, even with Node.js',
_10
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
_10
}

To send the message, pass the msg object as an argument to the helper library's send() method. You can also add then() and catch() methods to log the response status code and headers or catch and log any errors.


_10
sgMail
_10
.send(msg)
_10
.then((response) => {
_10
console.log(response[0].statusCode)
_10
console.log(response[0].headers)
_10
})
_10
.catch((error) => {
_10
console.error(error)
_10
})

The code block is now complete. To send the email message, you can run the index.js file with Node.js.


_10
node index.js

If you receive a 202 status code(link takes you to an external page) printed to the console, your message was sent successfully. Check the inbox of the “to” address, and you should see your demo message.

If you don't see the email, you may need to check your spam folder.

If you receive an error message, you can reference our response message documentation for clues about what may have gone wrong.

All responses are returned in JSON format. We specify this by sending the Content-Type header. The Web API v3 provides a selection of response codes, content-type headers, and pagination options to help you interpret the responses to your API requests.

(information)

Info

Get additional onboarding support. Save time, increase the quality of your sending, and feel confident you are set up for long-term success with our Email API Onboarding guide.


This is just the beginning of what you can do with our APIs. To learn more, check the resources below.


Rate this page: