Sending Email from Lambda
A lambda function can be triggered whenever something changes in S3 bucket. This note describes how to setup the lambda to send email on S3 Bucket update.
Create Lambda
Create lambda with following code.
'use strict';
const AWS = require('aws-sdk');
const sns = new AWS.SNS()
exports.handler = (event, context, callback) => {
console.log(process.env);
// This reads the environment variable 'sns_topic_arn'
var topic_arn = process.env.sns_topic_arn
var publishParams = {
TopicArn: topic_arn,
Message: JSON.stringify(event, null, 2)
};
sns.publish(publishParams, (err, data) => {
if (err) console.log(err)
else callback(null, "Completed");
})
};
Note: Please use Node version 14.x
Set Trigger Source
While creating lambda function, it provides the trigger source. Select S3 Bucket there.
Amazon provides SNS (Simple Notification Service) resource for sending email notification. Let’s setup SNS.
Setting up SNS
Create a SNS topic with the name onS3BucketChange
(name can be different).
Create a subscription where you need to add email address where to send the notification to.
Once the email address is added, a mail will be send to that email for subscription confirmation.
This should be enough for SNS. Let’s go back to Lambda. As we are using SNS in lambda, we have to provide permission to lambda to use SNS feature.
When you create lambda function, you get a role for that lambda created.
Add SNS policy for lambda
Go to roles window and select role for lambda. Add one more policy for lambda role AmazonSNSFullAccess
.
That’s it. Lambda can access SNS feature.
Configure Environment variable
We have used sns_topic_arn
environment variable in the code. Go to Environment variables tab and add environment variable by putting ARN for SNS topic that we get from Topic dashboard.
We are good to go for testing.