DEV Community

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

Posted on

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.

Top comments (1)

Collapse
 
dotenv profile image
Dotenv

💛🌴