# How to send emails using Amazon SES in Node.js

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jan 28, 2019, updated Sep 29, 2022. Topics: Node.js, Amazon Web Services.
Canonical URL: https://attacomsian.com/blog/amazon-ses-integration-nodejs

> A practical guide to learn how to use Amazon Simple Email Service (SES) to send emails in Node.js.

Amazon SES (Simple Email Service) is a popular cloud-based service for sending transactional and marketing emails. It integrates well with all popular programming languages. 

In this tutorial, I shall explain how to use this email service for sending transactional (or even marketing) emails in an Express.js/Node.js project.

> **Want to integrate AWS SES in Spring Boot project?** [Follow this tutorial](https://attacomsian.com/blog/amazon-ses-integration-with-spring-boot) for step-by-step instructions.

## AWS SES Setup

To use AWS SES in your project, you must have:

* An AWS account with full access to SES service (you need to create a support ticket to remove sandbox restrictions)
* A verified email address or domain name you want to use for sending emails

If you need help, [follow these instructions](https://attacomsian.com/blog/amazon-ses-integration-with-spring-boot#setup-amazon-ses) to complete the setup.

> ? **[Try Amazon SES with EmailOctopus](https://attacomsian.com/go/emailoctopus)** &mdash; A low-cost email marketing platform offering high deliverability, customized reports, and the ability to drip email sequences, import contacts, and integrate with forms.

## Create a Node.js Project

Let us create a new Node.js project and install all the required dependencies. We will use the official [AWS SDK](https://aws.amazon.com/sdk-for-node-js/) for JavaScript to call SES email service API.

```bash
$ npm init -y
$ npm install express body-parser aws-sdk --save
```

The `-y` flag will skip the questionnaire and create a default `package.json` file project in the root directory.

## Sending Emails using AWS SES API

Create a `ses-client.js` file in your project root directory with the following content:

<p class="file-desc"><span>ses-client.js</span></p>

```javascript
const AWS = require('aws-sdk');

const config = require('./config'); // load configurations file

AWS.config.update({
    accessKeyId: config.aws.key,
    secretAccessKey: config.aws.secret,
    region: config.aws.ses.region
});

const ses = new AWS.SES({apiVersion: '2010-12-01'});

const sendEmail = (to, subject, message, from) => {
    const params = {
        Destination: {
            ToAddresses: [to]
        },
        Message: {
            Body: {
                Html: {
                    Charset: 'UTF-8',
                    Data: message
                },
                /* replace the Html attribute with the following if you want to send plain text emails. 
                Text: {
                    Charset: "UTF-8",
                    Data: message
                }
             */
            },
            Subject: {
                Charset: 'UTF-8',
                Data: subject
            }
        },
        ReturnPath: from ? from : config.aws.ses.from.default,
        Source: from ? from : config.aws.ses.from.default,
    };

    ses.sendEmail(params, (err, data) => {
        if (err) {
            return console.log(err, err.stack);
        } else {
            console.log("Email sent.", data);
        }
    });
};

module.exports = {sendEmail};
```

In the above file, we have created a function called `sendEmail` that can be invoked from anywhere in the Node.js application to send an email via SES API. 

Now create a `config.js` file in the root directory and specify the AWS access key, access secret, and other required information.

<p class="file-desc"><span>config.js</span></p>

```javascript
module.exports = {
    'aws': {
        'key': 'YOUR_ACCESS_KEY',
        'secret': 'YOUR_ACCESS_SECRET',
        'ses': {
            'from': {
                // replace with an actual email address
                'default': '"Example.com" <noreply@example.com>', 
            },
            // e.g. us-west-2
            'region': 'YOUR_ACCESS_REGION' 
        }
    }
};
```

## Create `server.js` File

Let us create a `server.js` file in our project root directory that will be used to run our Node.js application:

<p class="file-desc"><span>server.js</span></p>

```javascript
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

const sesClient = require('./ses-client');

app.use(bodyParser.urlencoded({ extended: false }));  
app.use(bodyParser.json());

app.get('/', (req, res) => {
    // call sesClient to send an email
    sesClient.sendEmail('user@example.com', "Hey! Welcome", "This is the body of email");
    
    res.send('Email is sent!');
});

app.listen(3000, () => {
    console.log('App is listening on port 3000');
});
```

> **Source code:** Download the complete source code from [GitHub](https://github.com/attacomsian/code-examples/tree/master/nodejs/ses-nodejs) available under MIT license.

## Run the Application

To execute the project, run the following command in the terminal:

```bash 
$ npm run start
```

It will start the application server listening on port `3000` for connections. To test the solution, open the following URL in your browser window: `http://localhost:3000`. It is only a basic example to test the solution.
