A complete walkthrough: Sending Emails with Nodejs Using SendGrid

This article demonstrates how to send emails with Nodejs using SendGrid.

· 6 min read
Mary Maina

Mary Maina

I am a frontend engineer passionate about building intuitive user interfaces. Tools: React, Next.JS, TypeScript, React Native, NodeJs

topics

Email sending has become a popular business feature in modern business operations. With the adoption of digital communication, most businesses use email as a primary channel to share important business information such as promotional offers, newsletters, service updates, and transactional notifications.

In this post, we will explore how to send emails with Nodejs and Express using SendGrid. We’ll walk through configuring your Node.js application, integrating SendGrid’s API, and crafting personalized email messages to be dispatched seamlessly through your Express web server.

SendGrid Overview

SendGrid is an STMP service provider that offers robust APIs for sending emails without maintaining email servers. SMTP is a standard protocol used for sending email messages between the sender's and the recipient’s email server. SendGrid provides features like email templates, analytics, and scalability, enabling businesses to integrate email functionality into their applications.

Features of SendGrid

  1. SendGrid provides real-time tracking of emails, such as email delivery status, spam reports, unique opens and clicks, bounce rates, and email unsubscribers.
  2. SendGrid provides high email delivery in large-scale marketing with unique features such as email validation, integrated email tests, and dedicated IP addresses.
  3. SendGrid provides built-in email templates for quickly drafting and personalizing promotional emails. It also has a rich HTML editor and drag-and-drop editor for users who prefer to customize emails from scratch.
  4. SendGrid’s SMTP service streamlines the automation of transactional emails leveraging on the percentage of recipients who open or view an email out of the total number of emails delivered.
  5. SendGrid SMTP relay and Web API provide easy SendGrid integration with tools such as Twilio, Google Cloud Platform, and Airtable. This feature addresses business needs and enhances the email marketing experience.

SendGrid Setup

Create a SendGrid account

The first step in using SendGrid services is setting up a SendGrid account. Go to the SendGrid website and create a free account if you haven’t already created one. After signing in you should see a default SendGrid dashboard view.

Set up your email or domain with SendGrid

From the main dashboard, go to the “Settings” section and choose “Sender Authentication” from the dropdown menu. In this section, you define which email accounts are authorized to send emails via SendGrid.

  • Domain Authentication: This option allows you to authenticate your domain with SendGrid, authorizing it to send emails on your behalf. This is the recommended approach: https://docs.sendgrid.com/ui/sending-email/dmarc
  • Single Sender Authentication: This method allows you to authenticate a single email address for sending emails through SendGrid.

Image

Set up API Key

After verifying the sender, navigate to the Settings tab, proceed to “API Keys”, and click on the "Create API Key” button. This action will generate an API Key, used to grant permission to send emails. Add the API key name and choose the permission level according to your business needs. I gave my API key full permission.

Image

Create Project

Setting up our Nodejs project involves the following steps

  1. Install Node.js: Ensure that Node.js is installed on your machine. You can download the installer from the official Node.js website (https://nodejs.org/) and follow the installation instructions.
  2. Initialize the Project: Open your terminal or cmd and navigate to the directory where you want to create the project. Use the following command to initialize a Nodejs project with the default settings.

npm init -y

3. Install dependencies: Once the project is initialized install all the dependencies you need for your project. In our case, we shall install Typescript Express, dotenv, and SendGrid.

npm i express dotenv @sendgrid/mail

//generate tsconfig.json file
npx tsc --init 

//typescript and its dependencies
npm i --save-dev typescript @types/node

//nodemon to watch for file changes
npm i –save-dev nodemon 

4. Configure project settings: Configure a.env file to store our sensitive information such as the SendGrid API key. The environment variable file gets loaded into the project using the dotenv package.

5. Create project files: Create the necessary folders and files for your project. In our case, we shall create a src folder with the main entry file of our application and a utility folder that will contain a file that will handle the 'send email' logic

Image

Sending Emails

Importing the SendGrid module allows us to use methods for sending emails. The API key verifies the identity of the sender when making requests to the SendGrid API key. This code encapsulates the logic for sending emails using SendGrid.

The components of the email message which is returned by the getMessage function

  1. to: It specifies the recipient of the email.
  2. from: It specifies the email address of the person or domain sending the email.
  3. subject: It specifies the title of the email content, providing recipients with an idea of what the email is about.
  4. text: This key represents the plain text content of the email.
  5. html: It specifies the main body of the email in HTML format. This content is typically displayed to recipients who prefer to view emails with HTML rendering enabled.

//sendEmail.ts
import sendgrid from "@sendgrid/mail";

sendgrid.setApiKey(process.env.SENDGRID_API_KEY as string);
interface EmailProps {
  to: string;
  from: string;
  subject: string;
  text: string;
  html: string;
}
const sendEmail = ({ to, from, subject, text, html }: EmailProps) => {
  const message = { to, from, subject, text, html };
  return sendgrid.send(message);
};

export default sendEmail;

The index.ts file sets up an express server that listens for POST request on the 'api/test-email' endpoint. When a request is received, it sends a test email using SendGrid by calling the sendEmail function from the sendEmail module.

import express, { Request, Response } from "express";
import dotenv from "dotenv";
import sendEmail from "./utils/sendEmail";

dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;

function getMessage() {
  const body =
    "This is a test email using SendGrid from Node.js. It is working!!";
  return {
    to: process.env.CLIENT_EMAIL as string,
    from: process.env.SENDER_EMAIL as string,
    subject: "Test email with Node.js and SendGrid",
    text: body,
    html: `<strong>${body}</strong>`,
  };
}

app.post("/api/test-email", async (_req: Request, res: Response) => {
  try {
    await sendEmail(getMessage());
    res.status(200).send({
      message: "Email sent successfully!",
    });
  } catch (error: any) {
    console.error(error.message);
    res.status(500).send({
      message: "Email not sent!",
      error: error?.message,
    });
  }
});
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

GitHub Link : https://github.com/kodaschool/nodejs-sendgrid-integration

share

Mary Maina

I am a frontend devloper