Triggering AWS Lambda with SES Upon Email Received
Recently, we completed a project at the office where we triggered Lambda using AWS SES’s email receiving feature. I thought of creating a step-by-step blog for you all on how we did it.
Tools used in the project
- AWS SES
- Lambda
Perquisite for this:
Domain/Email
Lambda Function:
In this step we will create lambda function which will be triggering when we receive email. Goto Lambda function and click create function
Create function as per below details:
Paste the below code to Lambda function
import json
def lambda_handler(event, context):
# TODO implement
return {
'statusCode': 200,
'body': json.dumps('This is from SES')
}
Setup Of AWS SES:
First, we need to set up AWS SES, and after that, you’ll have to configure the identity on SES.
For that Go to Identities
Click on Create Identity
You can use Domain if you have domain otherwise use emailaddress. In case of domain it will give you DKIM keys which you may need to create a
Once you domain is added. Please go to your domain hosting and create 3 entries for CNAME there. After that your domain will be verified and ready to use.
You need to add the mx record into the domain hosting to route your emails. You can refer to this article for details Read. Please ensure that the region is the same as the one where you will be using the email receiving resource.
Next go to AWS SES and click on email receiving.
Select Receipt rule sets and then create rule set
Give it any name and click rule set
Once the rule set is created make sure rule is active
Click on create rule set and give it any name you like
In second step write the email on which you wish to receive email
In Add action set kindly select the lambda function we created in first step
Once created. Send email to receipt email and Lambda will trigger . you can check the logs of the lambda in the cloudwatch.
Thanks for reading. If you wish to restrict the email to only single email so please add one more lambda and paste the below code. Remember to change the header.value
exports.handler = function(event, context, callback) {
console.log('Header matcher');
var sesNotification = event.Records[0].ses;
console.log("SES Notification:\n", JSON.stringify(sesNotification, null, 2));
// Iterate over the headers
for (var index in sesNotification.mail.headers) {
var header = sesNotification.mail.headers[index];
// Examine the header values
if (header.name === 'From' && header.value === 'a b <ab@mail.com>') {
console.log('Found header with value.');
callback(null, null);
return;
}
}
// Stop processing the rule if the header value wasn't found
callback(null, {'disposition':'STOP_RULE'});
};