Thumbnail

How to Send an Email Using Amazon SES in Node.js

2024-03-25

||

6 mins read

Amazon SES, or Simple Email Service, is a cloud-based email sending service provided by Amazon Web Services. It's designed to help businesses and developers send emails reliably, efficiently, and at scale. Whether you need to send transactional emails, marketing campaigns, Amazon SES has got you covered. With features like easy integration, high deliverability rates, and flexible pricing options, it's a popular choice for organizations of all sizes.

I'll show you how to use Amazon SES in your Node.js applications, so you can start sending emails with confidence. Let's dive in and explore the world of Amazon SES together!

Step 1: Creating a user in AWS IAM with permission to access amazon SES

  1. Open the IAM Console: Once signed in, navigate to the IAM Console by selecting "Services" in the top left corner, searching for "IAM" and selecting it from the results.
aws console
  1. Navigate to Users: In the IAM Dashboard, click on "Users" in the left-hand menu to view existing users or create new ones.
iam dashboard
  1. Create a New User: Click on the "Add user" button to start creating a new user.
users page in iam
  1. Enter User Details: Enter a username for the new user.
create user page in iam
  1. Set Permissions: In the "Set permissions" step, choose attach policies directly to the user. Since we want to grant access to SES service, we'll attach policy AmazonSESFullAccess directly and click Next and click Create User.
create user page in iam
  1. Create Access Key and Secret Access Key: In the Users tab, click the user that we have just created.
users page in iam

Click on "Create access key".

user page in iam

Copy the Access key and Secret access key and keep it safe and click "Done".

access key creation in iam

Step 2: Setting up Amazon SES

  1. Open the Amazon SES Console: Once signed in, navigate to the Amazon SES Console by selecting "Services" in the top left corner, searching for "amazon simple email service" and selecting it from the results and make sure you are in the right region.
services search in Iam

click "Get Started".

  1. Adding your email address: Enter your email address from which you want to send the email.
setup page of ses
  1. Adding your sending domain: Enter your domain or subdomain. You need to have access to the DNS settings of your domain to verify it. We won't be covering that part in this post since the main aim is to send emails through Node.js using the AWS SDK. We will be able to send emails using just the email address. However, if you want to send emails from your domain, like "rohan@example.com," you need to verify your domain.
setup page of ses
  1. Step 3 is optional if you are going to send mail from your own email. In the future, if you need to send emails via your domain, you can do so by adding your domain in the "Identities" section in the AWS SES console.
  2. In Step 4 review the details you have entered and click "Get Started". A verification email will be sent to the email address you have entered. Click on the link to verify your email.
  3. Since we have just started, we will only get sandbox access. In the sandbox, we will only be able to send emails to verified email addresses and only 200 emails per day, which is enough for us to start. Once we are ready, we can request production access.
  4. Add more emails to send mails:To add more email addresses to send mails to, go to the Identities tab.
aws ses console
  1. Click on "Create Identity" to add email.
aws ses console
  1. Select "Email address", enter the email address, and check the box for "Assign a default configuration set." Then, click "Create Identity," and you will receive an email to verify your email.
aws ses create identity

Step 3: Creating a NodeJs Project

You can create a new NodeJs project using the npm init command. Open your terminal or command prompt on any empty folder and run the following command:

npm init -y

Step 4: Install AWS SES sdk

Now we need to install @aws-sdk/client-ses to connect with aws and dotenv to use environment variables.

npm install @aws-sdk/client-ses dotenv

Step 5: Initial Setup

project structure

The above is the structure of the application.

  1. Setting Up: First, we set up our environment by importing necessary modules and configuring our AWS credentials securely.
NEXT_PUBLIC_AWS_ACCESS_KEY_ID=
NEXT_PUBLIC_AWS_SECRET_ACCESS_KEY=

.env

  1. Creating SES Client: We then create a "client" that allows us to communicate with Amazon SES. Think of it as our messenger to send emails.
require("dotenv").config();
const { SESClient, SendEmailCommand } = require("@aws-sdk/client-ses");

const REGION = "ap-south-1"; //e.g. "us-ea st-1"
const ACCESS_KEY = process.env.NEXT_PUBLIC_AWS_ACCESS_KEY_ID;
const SECRET_KEY = process.env.NEXT_PUBLIC_AWS_SECRET_ACCESS_KEY;

const client = new SESClient({
  region: REGION,
  credentials: {
    accessKeyId: ACCESS_KEY,
    secretAccessKey: SECRET_KEY,
  },
});

index.js

  1. Email Content: Next, we define what our email will say. This includes the subject line and the actual message, both in plain text and HTML format.
// subject of the email
SUBJECT = "Amazon SES Test";
// The email body for recipients with non-HTML email clients.
BODY_TEXT =
  "Amazon SES Test\r\nThis email was sent with Amazon SES using the AWS SDK.";
// The HTML body of the email.
BODY_HTML =
  "<html><body><h1>Amazon SES Test</h1><p>This email was sent with <a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the AWS SDK</p></body></html>";

index.js

  1. Configuring Recipients: We specify who will receive our email, both their email addresses and any special settings we want to apply.

const input = {
  Source: "example@somedomain.com", // email from which you want to send the email
  Destination: {
    ToAddresses: ["name@gmail.com"], // list of emails to send the mail
  },
  Message: {
    Subject: {
      Data: SUBJECT,
      Charset: "UTF-8",
    },
    Body: {
      Html: {
        Data: BODY_HTML,
        Charset: "UTF-8",
      },
      Text: {
        Data: BODY_TEXT,
        Charset: "UTF-8",
      },
    },
  },

  ConfigurationSetName: "my-first-configuration-set", // get configuration set from you aws ses console
};

index.js

  1. Sending the Email: Finally, We use the SES client we created earlier to send our email, and if everything goes smoothly, we'll see a confirmation that our email was sent.
client
  .send(new SendEmailCommand(input))
  .then(() => {
    console.log("Email Sent");
  })
  .catch((error) => {
    console.log(error);
  });

index.js

The complete code of the index.js page

require("dotenv").config();
const { SESClient, SendEmailCommand } = require("@aws-sdk/client-ses");

const REGION = "ap-south-1"; //e.g. "us-ea st-1"
const ACCESS_KEY = process.env.NEXT_PUBLIC_AWS_ACCESS_KEY_ID;
const SECRET_KEY = process.env.NEXT_PUBLIC_AWS_SECRET_ACCESS_KEY;

const client = new SESClient({
  region: REGION,
  credentials: {
    accessKeyId: ACCESS_KEY,
    secretAccessKey: SECRET_KEY,
  },
});

// subject of the email
SUBJECT = "Amazon SES Test";
// The email body for recipients with non-HTML email clients.
BODY_TEXT =
  "Amazon SES Test\r\nThis email was sent with Amazon SES using the AWS SDK.";
// The HTML body of the email.
BODY_HTML =
  "<html><body><h1>Amazon SES Test</h1><p>This email was sent with <a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the AWS SDK</p></body></html>";

const input = {
  Source: "example@somedomain.com", // email from which you want to send the email
  Destination: {
    ToAddresses: ["name@gmail.com"], // list of emails to send the mail
  },
  Message: {
    Subject: {
      Data: SUBJECT,
      Charset: "UTF-8",
    },
    Body: {
      Html: {
        Data: BODY_HTML,
        Charset: "UTF-8",
      },
      Text: {
        Data: BODY_TEXT,
        Charset: "UTF-8",
      },
    },
  },

  ConfigurationSetName: "my-first-configuration-set", // get configuration set from you aws ses console
};

client
  .send(new SendEmailCommand(input))
  .then(() => {
    console.log("Email Sent");
  })
  .catch((error) => {
    console.log(error);
  });

index.js

We can use the below command to run the file and send the email.

node index.js

You can find the source code here.