How to send emails in NodeJS using SendGrid

Short and sweet guide on how to send emails using sendgrid in a Node.js application.

How to send emails in NodeJS using SendGrid

Step 1: Create a SendGrid account

Create a SendGrid account at this link. Fill all the required details and after successfully creation of your account, you will see a page like below.

Ignore the contents of this page and follow the next step.

Step 2 : Create your API Key

In the left menu under Settings tab, click on API Keys.

Next click on Create API Key blue button on top right corner of your screen. A drawer will slide from right side of your screen and you will be asked to enter API key name and API key permissions.

Fill any arbitrary value in API key name field and choose Full Access under API Key Permissions. Click Create & View to successfully create your first API key.

Your API Key has been created. IMPORTANT! Please save the key somewhere like in a notepad as you won't be able to see the key again. In case you forgot to save the key, you will have to create a new API Key again.

Step 3 : Sender Authentication

SendGrid requires you to verify the email address you will use to send emails through your Nodejs app. Again in the left menu under Settings tab, click on Sender Authentication

Click on Get Started button corresponding to Single Sender Verification below Verify an Address. You will see a form like below.

For simplicity, let the From email address and Reply To field be the same as the one you used for signing up. Also ignore any warning messages such as "Attempting to send from a free email address domain like gmail.com is not recommended."

Click on create button and go to your inbox to verify the email address. On Single Sender Verification page, check whether the verified column turned from red cross to green tick.

Now that we have successfully created our API Key and verified our sender email address lets jump into the code!

Step 4: Code

Install the sendgrid npm package.

npm install @sendgrid/mail

I have written a simple express app below with a single GET route that will send an email when called.

const express = require('express');

const app = express();
const PORT = process.env.PORT || 8080;

app.get("/email", (req, res) => {
  res.send("Working!");
})

app.listen(PORT, () => console.log(`Listening on PORT: ${PORT}`))

Require the @sendgrid/mailpackage in your code and set the API Key given to you in Step 2 like below.

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(/* Your API Key here */);

Now add the following code inside your /email route handler.

const msg = {
  to: "foo@bar.com",
  from: 'foor@bar.com',
  subject: 'Subject of your EMAIL here',
  text: "This is a test email!",
  html: "<strong>You can also send html code</strong>"
};

sgMail.send(msg)
.then(() => { })
.catch(error => {
  console.error(error);
  if (error.response) {
    console.error(error.response.body)
  }
})

Remember to replace the from value with the email address you provided in Step 3 : Sender Authentication and to value with any valid email address to check whether you received the email.

Your final code should look like this :

const express = require('express');

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(/* Your API Key here */);

const app = express();
const PORT = process.env.PORT || 8080;

app.get("/email", (req, res) => {
  // Send email
  const msg = {
    to: "foo@bar.com",
    from: "foor@bar.com",
    subject: "Subject of your EMAIL here",
    text: "This is a test email!",
    html: "<strong>You can also send html code</strong>"
  };
  sgMail.send(msg)
  .then(() => { })
  .catch(error => {
    console.error(error);
    if (error.response) {
      console.error(error.response.body)
    }
  })
  res.send("Working!");
})

app.listen(PORT, () => console.log(`Listening on PORT: ${PORT}`))

IMPORTANT! Do not expose your SendGrid API Key on github or anywhere on the internet. If you expose your API Key on github, SendGrid suspends your account automatically and you won't be able to send emails anymore.

Congratulations!

You just successfully sent your first email using Node.js if you haven't encountered any errors so far. You can also check out the SendGrid docs if you are looking more than just sending text emails.

Shubham Nazare is a Full Stack Developer based out of Mumbai, India.