DEV Community

Cover image for Sending Email with Amazon SES on NodeJS
Juha
Juha

Posted on

1

Sending Email with Amazon SES on NodeJS

Here's a quick example of sending an email with Amazon SES (Simple Email Service).

In this example we are using a few libraries:

  • Nodemailer provides support for embedded images etc.
  • EJS is a templating library, which we use to build our HTML email
  • dotenv loads environment variables from a .env file

Install them:

npm install @aws-sdk/client-ses dotenv ejs nodemailer
Enter fullscreen mode Exit fullscreen mode

Provide your AWS region and secrets in your .env file:

AWS_REGION=eu-central-1
AWS_ACCESS_KEY_ID=AKIAX...
AWS_SECRET_ACCESS_KEY=HMZHQ...
Enter fullscreen mode Exit fullscreen mode

Create a simple HTML email template my-email.ejs:

<h1>Hi there</h1>
<p>This email is sent using Amazon SES with NodeJS. Nice!</p>
Enter fullscreen mode Exit fullscreen mode

Create the javascript index.js for sending the email:

import 'dotenv/config';
import * as aws from "@aws-sdk/client-ses";
import nodemailer from "nodemailer";
import * as ejs from "ejs";

const sesClient = new aws.SESClient({
    region: process.env.AWS_REGION,
    credentials: {
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
    }
});

const transporter = nodemailer.createTransport({
    SES: {
        ses: sesClient,
        aws: aws
    }
});

const mailHtml = await ejs.renderFile('./my-email.ejs');

transporter.sendMail({
        from: "sender@example.org",
        to: "receiver@example.org",
        subject: "Hello there via Amazon SES",
        html: mailHtml
}, (err, info) => {
        console.log(info.envelope);
        console.log(info.messageId);
});
Enter fullscreen mode Exit fullscreen mode

If you get trouble with the import statements, you might need to add this to your package.json:

...
"type": "module",
...
Enter fullscreen mode Exit fullscreen mode

There we go. This is a quick reference for developers looking to integrate Amazon SES using NodeJS.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
dotenv profile image
Dotenv

💛🌴

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay