Automate Incoming Email Processing with Amazon SES & AWS Lambda
If you use Amazon SES to receive email, it’s probably not the kind of email that you want to end up in someone’s personal inbox to be manually read using a traditional email client. The most common use case for receiving mail in SES is to handle it automatically. Emails like contact@example.com or unsubscribe@example.com fall in this category. This article describes how to set up SES to receive email & process it automatically.
Step 1 — Create a Rule Set
Start by creating a rule set as shown below:
You can also create an S3 bucket from the above screen, which will also add a bucket policy to that bucket to allow SES to write to it. But if you select an existing bucket, remember to add a bucket policy to it to allow writes from SES.
The idea here is to first write all incoming emails to S3, then run a Lambda function to fetch those emails from S3 & process them.
Step 2 — Create the Lambda Function
Next, create the Lambda function to fetch the email from S3 & process it as needed. Here’s a sample:
var AWS = require('aws-sdk');
var S3 = new AWS.S3();
exports.handler = function (event, context, callback) {
S3.getObject({
Bucket: 'my-bucket',
Key: event.Records[0].ses.mail.messageId
}, function (err, data) {
if (err) callback(err);
else {
// process email (data.Body) here
callback(null, null);
}
});
};
About the Author
Harish KM is an AWS Developer at QloudX. He is passionate about creating zero-maintenance fully-serverless cloud-native solutions in AWS. With 20+ cloud & IT certifications, he is an expert in a multitude of technologies, especially serverless.