Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using AWS Lambda to Send SES Notifications Triggered by S3 Events

DZone's Guide to

Using AWS Lambda to Send SES Notifications Triggered by S3 Events

AWS Lambda's event handling abilities make it ideal to serve as a serverless listener. Events from your S3 bucket can be used to send email alerts with ease.

· Cloud Zone
Free Resource

MongoDB Atlas is a database as a service that makes it easy to deploy, manage, and scale MongoDB. So you can focus on innovation, not operations. Brought to you in partnership with MongoDB.

Image title

Sometimes we want to get notifications when an event occurs in an AWS S3 bucket, like a file upload, deletion, etc.

The event handling capability of AWS Lambda can come handy in such a situation, and we will involve SES (Amazon Simple Email Service) in this demo.

Let's go through the steps.

The S3 Bucket

Have an S3 bucket in place. It will look like:

Here, for the example's sake, we will use the bucket listed as ‘namit’.

The Lambda Function

Next comes the Lambda function. It will play the role of an event listener:

Lambda     -->    New function

The Code

You can refer to the below code to replace the Lambda template (Node.js):

var aws = require('aws-sdk');
var ses = new aws.SES({
    region: 'us-west-2'
});
const s3 = new aws.S3({
    apiVersion: '2006-03-01'
});
exports.handler = function(event, context, callback) {
    console.log("Incoming: ", event);
    const bucket = event.Records[0].s3.bucket.name;
    const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const news = `Event took place in - ${bucket} -> ${key}`;
    const params = {
        Bucket: bucket,
        Key: key,
    };
    var eParams = {
        Destination: {
            ToAddresses: ["testingxxxxx@gmail.com"]
        },
        Message: {
            Body: {
                Text: {
                    Data: `${news}`
                }
            },
            Subject: {
                Data: "Email Notification"
            }
        },
        Source: "testingxxxxx@gmail.com"
    };
    console.log('===SENDING EMAIL===');
    var email = ses.sendEmail(eParams, function(err, data) {
        if (err) console.log(err);
        else {
            console.log("===EMAIL SENT===");
            // console.log(data);
            console.log("EMAIL CODE END");
            console.log('EMAIL: ', email);
            context.succeed(event);
        }
    });
};


Make sure you replace the email ID with the one you intend to use. Next, a brief look at the configuration and trigger for the Lambda:

When enabled, the Lambda function will start receiving event notifications from the S3 bucket it is bound to. Along with the above code, some policy and permission changes are required as well.

For the above sample, we can use the following policy structure in IAM:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents",
                "ses:SendEmail",
                "ses:SendRawEmail"
            ],
            "Resource": "*"
        }
    ]
}


And make sure the email ID we are using has been verified first in SES:


Upload a sample file in the S3 bucket: 'namit' -> green.jpg

Check the CloudWatch and the email account used. 

BINGO! We have mail with:

Subject: Email Notification

Body: Event took place in - namit -> green.jpg

Let’s disable the Lambda function now, and we'll think of a different use case.

MongoDB Atlas is the best way to run MongoDB on AWS — highly secure by default, highly available, and fully elastic. Get started free. Brought to you in partnership with MongoDB.

Topics:
aws lambda ,aws s3 ,listeners ,tutorial ,cloud

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}