How to Use SendGrid to Send Emails

John Au-Yeung
The Startup
Published in
15 min readOct 28, 2019

--

SendGrid is a great service made by Twilio for sending emails. Rather than setting up your own email server for sending email with your apps, we use SendGrid to do the hard work for us. It also decrease the chance of email ending up in spam since it is a known trustworthy service.

It also has very easy to use libraries for various platforms for sending emails. Node.js is one of the platforms that are supported.

To send emails with SendGrid, install the SendGrid SDK package by running npm i @sendgrid/mail . Then in your code, add const sgMail = require(‘@sendgrid/mail’); to import the installed package.

Then in your code, you send email by:

sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: email,
from: 'email@example.com',
subject: 'Example Email',
text: `
Dear user, Here is your email.
`,
html: `
<p>Dear user,</p> <p>Here is your email.</p>
`,
};
sgMail.send(msg);

where process.env.SENDGRID_API_KEY is the SendGrid’s API, which should be stored as an environment variable since it is a secret.

In this article, we will build an app that lets users enter email templates. Then they can use the templates to send emails to different email addresses. Our app will consist of a back end and a front end. The front end will be built with React, and the back end will be built with Express.

Back End

--

--