AWS SES in Node

Note: There are relatively easier ways like using SendGrid rather than AWS SES.

I recently read an instruction teaching developers how to implement AWS Simple Email Service within Node.js project. It lacks some information of AWS part. So below is my practice process:

Step 1: In AWS IAM, create a new user, give the user below authority only:

1
2
3
4
5
6
7
8
9
{
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ses:SendRawEmail",
            "Resource": "*"
        }
    ]
}


Step 2: Switch back to admin account, create a new credential key for the new user.



Step 3: In your Node.js project, create file “config.json” under a controller file in which you want to implement sending email functionality, below is the content of it, use the key created in step 2:

1
2
3
4
5
{
    "accessKeyId": <YOUR_ACCESS_KEY_ID>,
    "secretAccessKey": <YOUR_SECRET_ACCESS_KEY>,
    "region": <YOUR_AWS_REGION>
}


Step 4: In your AWS admin account, find SES console, then verify your company’s email address, if you only want to have a test, you could use your Gmail. This verification is actually AWS requests authority from your Gmail, so your Node app can utilize SES, then SES can use your Gmail account to send emails on behalf of you:



Step 5: You have finished setting up your AWS, well done, now we could move on to our Node app. There are three modules we need to install:

1
npm i --save aws-sdk nodemailer nodemailer-ses-transport


Step 6: In auth controller for example, below is simplified code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const nodemailer = require('nodemailer');
const aws = require('aws-sdk');

const User = require('./models/user')

// configure AWS SDK
aws.config.loadFromPath('./config.json');

// create Nodemailer SES transporter
const transporter = nodemailer.createTransport({
    SES: new aws.SES({
        apiVersion: '2010-12-01'
    })
});

// send a register confirmation email in your middleware
exports.postRegister = (req, res, next) => {
    const email = req.body.email;
    const password = req.body.password;

    // create a new user
    const user = new User({
        email: email,
        password: password,
        isVerified: false,
    });
    user.save();
    res.redirect('/login');

    // send verification email
    transporter.sendMail({
            to: email,
            from: 'abc@example.com',
            subject: 'Register succeeded!',
            html: '<h1>You have just registered, please verify it, thanks</h1>'
    });
};


Leave a Reply

Your email address will not be published. Required fields are marked *