In this quickstart, you'll learn how to send your first email using the Twilio SendGrid Mail Send API and Node.js.
Be sure to perform the following prerequisites to complete this tutorial. You can skip ahead if you've already completed these tasks.
When you sign up for a free SendGrid account, you'll be able to send 100 emails per day forever. For more account options, see our pricing page.
Twilio SendGrid requires customers to enable Two-factor authentication (2FA). You can enable 2FA with SMS or by using the Authy app. See the 2FA section of our authentication documentation for instructions.
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.
export SENDGRID_API_KEY=<Your API Key>
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.
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.
The Twilio SendGrid Node.js helper library supports the current LTS version of Node.js and versions 6, 7, 8, and 10.
Check your Node.js version by opening your terminal (also known as a command line or console) and typing the following command:
node --version
If you have Node.js installed, the terminal should print something like the following output:
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 for instructions on downloading and installing a version appropriate for your operating system. The npm package manager also has a helpful installation guide.
Using a Twilio SendGrid helper library 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.
mkdir sgQuickstart
Next, navigate into the sgQuickstart directory where you will complete the rest of the tutorial.
cd sgQuickstart
The npm 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.
npm --version
The terminal should print something like the following output.
6.13.4
You can install the helper library using yarn if you prefer.
Before installing the package, you should first initialize your project with the following command.
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.
To install the Twilio SendGrid helper library, type the following command into the terminal.
npm install --save @sendgrid/mail
The terminal should print something like.
1$npm install --save @sendgrid/mail2+ @sendgrid/mail@7.2.13added 15 packages from 19 contributors and audited 15 packages in 1.625s4found 0 vulnerabilities
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.
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.
1const sgMail = require('@sendgrid/mail')2sgMail.setApiKey(process.env.SENDGRID_API_KEY)34const msg = {5to: 'test@example.com', // Change to your recipient6from: 'test@example.com', // Change to your verified sender7subject: 'Sending with SendGrid is Fun',8text: 'and easy to do anywhere, even with Node.js',9html: '<strong>and easy to do anywhere, even with Node.js</strong>',10}1112sgMail13.send(msg)14.then((response) => {15console.log(response[0].statusCode)16console.log(response[0].headers)17})18.catch((error) => {19console.error(error)20})
Your API call must have the following components:
https://api.sendgrid.com/v3/
)
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.
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.
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.
1const msg = {2to: 'test@example.com', // Change to your recipient3from: 'test@example.com', // Change to your verified sender4subject: 'Sending with SendGrid is Fun',5text: 'and easy to do anywhere, even with Node.js',6html: '<strong>and easy to do anywhere, even with Node.js</strong>',7}
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.
1sgMail2.send(msg)3.then((response) => {4console.log(response[0].statusCode)5console.log(response[0].headers)6})7.catch((error) => {8console.error(error)9})
The code block is now complete. To send the email message, you can run the index.js
file with Node.js.
node index.js
If you receive a 202
status code 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.
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.