How to send S3 event notification email using Lambda and SES?

Reading Time: 10 minutes

Email notifications are an important part of any modern application. In this blog, we will discuss how to send Email notifications using the Amazon SES service and AWS Lambda and will demonstrate how to send an acknowledgment email to a user using AWS Lambda and Amazon SES upon adding new objects in an S3 bucket.

In this blog, we will cover:

  • What is Amazon SES?
  • When to use Amazon SES?
  • Benefits of Amazon SES
  • Use Cases of Amazon SES
  • Hands-on – Send an Email notification (Using SES and Lambda) to the admin when any new objects get added into the S3 bucket
    • Create an S3 bucket (or use an existing bucket)
    • Create an IAM policy and an execution role (you can either create it by going to the IAM section on the console or you can choose the option of ‘create a default execution role with basic settings’ while creating a Lambda function)
    • Verify SES identity Domain OR Email – Either a domain bought from an external source or bought from AWS Route53. Email verification using the SES console
    • Create a Lambda function to write code for sending an Email using SES
    • At last, a trigger to the Lambda function with S3 Bucket as the source initiates its execution while adding a new object.
    • Add a new object in the S3 bucket and test the entire implementation to check how the Lambda function is invoking SES and sending notification emails.  

What is Amazon SES?

Amazon Simple Email Service (SES) is a cost-effective, flexible, and scalable email service that enables developers to send mail from within any application.

Amazon SES allows you to send and receive emails using our own email addresses and/or domains and we only pay for what you use. We can use this service for sending both transactional and mass emails. Amazon SES easily integrates with Amazon CloudWatch, Amazon SNS, AWS Lambda, Amazon EC2, AWS Elastic Beanstalk, AWS IAM, Amazon Route53, Amazon S3, etc.

You can configure Amazon SES quickly to support several email use cases, including transactional, marketing, or mass email communications. Amazon SES’s flexible IP deployment and email authentication options help drive higher deliverability and protect sender reputation while sending analytics to measure the impact of each email. With Amazon SES, you can send emails securely, globally, and at scale.

When to use Amazon SES?

As and when companies grow in size and in the economy, they sometimes yet rely on methods that don’t make sense anymore. For example, the way businesses process outgoing emails from email clients. Those emails include some essential reminders you might want to send to your customers. If the email is to be forwarded to a large audience (thousands of users), it gets difficult to use Google Gmail or some third-party applications because of the complexity of the infrastructure. This complexity depends on how business scales up or down as the demand changes. Since Amazon SES is designed to handle such scenarios as sending mass emails and providing detailed analysis, the service beats all the other email services in the market.

Benefits of Amazon SES

Let’s glance over the following major benefits of Amazon Simple Email Service one by one:

High Deliverability

Amazon SES provides you with Content filtering technologies, allows you to use dedicated IP, and comes with a fully secured dashboard to provide end-to-end analysis thus ensuring that messages reach your customers’ inboxes.

Cost-Effective

SES provides you with the flexibility of pay as you go, and pay just for what you utilize. It doesn’t charge you with any upfront fees, negotiations, advance payments, and no minimum charges. Amazon SES offers 62,000 emails each month for free sent from an application hosted on Amazon EC2.

Configurable

You can make use of the Rule Sets to make rules for the emails you send using Amazon SES. For example, create rules to store emails received in an Amazon S3 bucket or rules for Amazon CloudWatch to provide a more detailed analysis.

Reliable

Amazon SES runs on an extremely reliable Amazon Internet Services Infrastructure. There are numerous data centers and redundant systems that make sure to provide the highest levels of availability.

Apart from the above-mentioned major benefits, Amazon SES also provides the following benefits:

  • Ease of use
  • Interact with customers at scale
  • Optimization of delivery of emails
  • Increase the effectiveness
  • Communication easy with the use of automated replies
  • Scaling capabilities without any manual intervention

Use Cases of Amazon SES

There are many such applications of AWS SES, let’s discuss some of them:

Transaction Acknowledgment Emails

Amazon SES provides us with the ability to send automated emails to users which might include purchase information or shipping status notifications, etc.

Email Receival

Users can configure Amazon SES in such a way that it can perform an action on an email received. For example, emails sent to Amazon SES can be configured to be stored in an S3 bucket which in turn will trigger a lambda function to perform some other execution or Amazon SES can also be configured in such a way that on an email receival, it can trigger the execution of a lambda function.

Health Check Notifications

Amazon SES can also be configured and integrated easily with a service such as Elastic Beanstalk. For example, on any change in the health status of an application hosted on Elastic Beanstalk, Amazon SES can send emails alerting the user of the health status at each deployment stage.

  1. Lambda function is invoking SES and sending notification emails.  

Let’s do hands-on:

Let’s work on the scenario where we want to send a notification email to an admin when any user is uploading a new image in the S3 bucket. S3 acts as one of the triggers for AWS Lambda. We will use the Lambda function to write the code to send an acknowledgment email using Amazon SES. 

To implement this, we will do the following:

  1. Create an S3 bucket (or use an existing bucket)
  2. Create an IAM policy and an execution role (you can either create it by going to the IAM section on the console or you can choose the option of ‘create a default execution role with basic settings’ while creating a Lambda function)
  3. Verify SES identity Domain OR Email – Either a domain bought from an external source or bought from AWS Route53. Email verification using the SES console
  4. Create a Lambda function to write code for sending an Email using SES
  5. At last, a trigger to the Lambda function with S3 Bucket as the source initiates its execution while adding a new object.
  6. Add a new object in the S3 bucket and test the entire implementation to check how 
  7. Go to the S3 Console and click on Create Bucket as shown in the below screenshot: 
  1. Enter a name for the bucket. You can disable the ‘Block all public access’ checkbox if you want your bucket to be public. Also, you can add tags for objects added in the bucket or you can enable Bucket Versioning if required.
How to send S3 event notification email using Lambda and SES?

We are not enabling Bucket versioning and not adding any tags as of now. Click on Create Bucket as shown in the below screenshot. 

and you will see the bucket created as shown in the below screenshot:

How to send S3 event notification email using Lambda and SES?

Now, go to the IAM Console on AWS.

Under roles, create on ‘Create role’, choose ‘Lambda’ and click on Next:Permissions

How to send S3 event notification email using Lambda and SES?

Based on the AWS best practices, it is suggested that you create a policy with only the required permission. Click on Create policy as shown in the following screenshot:

How to send S3 event notification email using Lambda and SES?

Under JSON, add the following JSON as given below. Rename ‘mybucket’ to the bucket name you created above and click on ‘Review Policy’. 

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:PutLogEvents",
                "logs:CreateLogGroup",
                "logs:CreateLogStream"
            ],
            "Resource": "arn:aws:logs:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::mybucket/*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "ses:SendEmail",
                "ses:SendRawEmail"
            ],
            "Resource": "*"
        }
    ]
}         
How to send S3 event notification email using Lambda and SES?

Give a name to the policy and click on Create Policy

Upon the creation of the policy, go back to the tab where you were creating an execution role and click on the ‘refresh’ button. Search for the policy you just created and attach the newly created policy to the role and click on Next: Tags.

How to send S3 event notification email using Lambda and SES?

Enter Tags (key/value) if any. In this blog, we will not add any tag and click on Next: Review.

How to send S3 event notification email using Lambda and SES?

Review the policy attached and enter a role name. Once done, click on create role.

The role you just created will be visible under the roles section on the console.

How to send S3 event notification email using Lambda and SES?
  1. Now, open the Amazon SES Console as shown in the below screenshot:
How to send S3 event notification email using Lambda and SES?

Click on the ‘Email Addresses’ under ‘Identity Management’ on the left side.

How to send S3 event notification email using Lambda and SES?

Click on Verify a New Email Address and a modal will appear. Enter the email on which you want to receive emails. Remember that both the ‘sender’s and receivers’ email addresses will have to be verified to send and receive emails. 

For this exercise, we will verify one email address and use the same email address as sender and receiver.

How to send S3 event notification email using Lambda and SES?

Click on Verify This Email Address. You will then receive a verification email on the email address as shown in the below screenshot:

Upon clicking the link in the email received, you will get the message shown in the below screenshot:

How to send S3 event notification email using Lambda and SES?

On successful, your email address will be verified and will appear on the dashboard with the status verified as shown in the below screenshot:

How to send S3 event notification email using Lambda and SES?
  1. Now, open the AWS Lambda console. Select Functions mentioned in the left navigation pane as shown in the below screenshot. Click on Create Function
How to send S3 event notification email using Lambda and SES?

Select Author from scratch, enter the function name, select the runtime as Python 3.7 as shown in the following screenshot:

How to send S3 event notification email using Lambda and SES?

Under the Execution role, select Use an existing role and select the role you created above and click on Create Function.

Upon clicking on Create function, you will be navigated to the function console as shown in the below screenshot:

How to send S3 event notification email using Lambda and SES?

Now scroll down and under the function code in the editor pane, write the following code:

import boto3
from botocore.exceptions import ClientError
 
def lambda_handler(event, context):
    sender_email_address = 'sender's email address'
 
    receiver_email_address = 'receiver's email address'
 
    aws_region_name = "aws region"
 
    email_subject = "Subject name"
 
    html_body = ("<html>"
        "<body>"
        "<p>Dear Admin,</p>"
        "<br>"
        "<p>New Object Added in the bucket.</p>"
        "</body>"
        "</html>")
 
    charset = "UTF-8"
 
    ses_resource = boto3.client('ses', region_name = aws_region_name)
 
    try:
        response = ses_resource.send_email(
                Destination = {
                    'ToAddresses': [
                        receiver_email_address,
                    ],
                },
                Message = {
                    'Body': {
                        'Html': {
                            'Charset': charset,
                            'Data': html_body,
                        },
                    },
                    'Subject': {
                        'Charset': charset,
                        'Data': email_subject,
                    },
                },
                Source = sender_email_address,
            )
 
    except ClientError as e:
        print("Email Delivery Failed! ", e.response['Error']['Message'])
    else:
        print("Email successfully sent to " + receiver_email_address + "!")

In the above sample code:

  • Change the ‘sender’s email address’ to the email address using which you want to send the email.
  • Change the ‘receiver’s email address’ to the email address on which you want to receive the email.
  • Ensure that both the email addresses (sender and receiver) are verified on Amazon SES.
  • Change the ‘aws region’ based on the region you are operating in.
  • You can edit the ‘Subject Name’ and the ‘HTML Body’ as you want.

Since, we are using only a single email address in this blog, the senders and receivers email addresses are the same.

Click on the deploy.

  1. Now scroll back up and click on Add Trigger
How to send S3 event notification email using Lambda and SES?

Select ‘S3’ as the trigger, the bucket name which we have created at the beginning of the exercise, select the ‘Event type’ to ‘PUT’ and finally add prefix & suffix (if any) for your bucket.

How to send S3 event notification email using Lambda and SES?

Scroll down and click on Add

In the following screenshot, you can see the S3 trigger added on the lambda console.

How to send S3 event notification email using Lambda and SES?

click on deploy. Lambda function is ready to use now!

  1. Now, go back to the Amazon S3 console and get into the bucket which we have created in the beginning of the exercise
How to send S3 event notification email using Lambda and SES?

Click on Upload

Click on Add Files, attach the files you want to add in the bucket and click on upload. We will be uploading an image file shown below.

How to send S3 event notification email using Lambda and SES?

As soon as the image object is added to the bucket, it will trigger the Lambda function and the admin will receive an email on its email address as shown in the below screenshot:

Conclusion

In this blog, you have seen how easily we can configure Amazon Simple Email Service and we have used it to send notifications while any new objects get added to the S3 bucket. We have used the Lambda function to write code and configured triggers.  We will discuss more about serverless, Lambda, SES, and many more topics in our upcoming blog. Stay tuned to keep getting all updates about our upcoming new blogs on AWS and relevant technologies. 

For any further queries, feel free to post your comments, we are happy to help!

Meanwhile …

Keep Exploring -> Keep Learning -> Keep Mastering

This blog is part of our effort towards building a knowledgeable and kick-ass tech community. At Workfall, we strive to provide the best tech and pay opportunities to AWS-certified talents. If you’re looking to work with global clients, build kick-ass products while making big bucks doing so, give it a shot at workfall.com/partner today.

Back To Top