Configure Email Notifications With Amazon SES, Lambda and DynamoDB

4 min read

Laptop with various envelopes indicating email.

When it comes to managing your data in real time, automation is key to staying one step ahead. Setting up your DynamoDB database to send email alerts whenever a new record is added ensures instant updates, streamlines notifications and empowers your team to take immediate action. By using Amazon Simple Email Service (SES) and AWS Lambda, you can create a seamless, cost-effective system that eliminates manual monitoring and improves workflow efficiency.

Whether you’re tracking new user sign-ups, processing transactions or monitoring critical logs, this setup keeps you informed the moment change happens, eliminating the worry of delays, so you can receive actionable insights delivered straight into your inbox.

Here’s how to set up your DynamoDB database to send email alerts whenever a new record is entered into the database, using SES and a lambda function.

What is a lambda function, you may ask? It is a function that is defined without a name, and is also known as an anonymous function. Lambda functions can be used in a variety of programming languages, including Python, Excel and C++.

AWS Services Used in This Demonstration:

Fast and fully managed, Amazon DynamoDB is a NoSQL database that stores data as key-value pairs. When a new record is added to the database, a trigger that we use as an event source will be set off.

Amazon SES is a cloud-based email solution enabling the integration of a bulk email provider. Following a user’s registration, which results in the insertion of a new record, we will use this AWS service to send the email notification.

The serverless computing service Amazon Lambda will house the logic code that we will use to control when SES should deliver a notice following an event trigger.

Project Requirement

A functioning AWS account is required to complete this tutorial. If you don’t have this already set up, you can create an account by visiting the AWS website. Don’t worry about paying for this demo; even a free-tier account can work wonders.

Set Up Amazon SES

  • Go to Services and Navigate to the Amazon SES console after successfully logging in to your account.
  • Create configuration sets (optional)
  • Create and verify an identity (domain or email address). We will use an email address for simplicity, but if you own a domain, kindly try that too. You just need to verify ownership of the domain.
  • Select the email address. (This will be used as the sender address for your email notifications.)
  • After email verification, your set email should appear in the list of verified identities.

Amazon Lambda Function Setup

  • Navigate to the AWS Lambda console in your account and create a function from scratch. Provide a name for your function.
  • The next step is to choose a runtime environment (Python, Node.js, Java, etc.). For this demo, we’ll use Python code, but you can choose an alternative language of your choice.
  • Set up the function’s execution role with the needed permissions.

In this demo, the lambda function will need read access to the DynamoDB table and access to SES to send the email notification. The “dynamodb-ses-role” custom role I am using has the following permissions:

  • AmazonDynamoDBFullAccess
  • AmazonSESFullAccess

Write the lambda function code to handle the DynamoDB stream event and enable sending email notifications via Amazon SES.

Below is the script of my Python lambda code to achieve the above requirements.

import boto3
def lambda_handler(event, context):
# Extract relevant information from the DynamoDB trigger event
for record in event[‘Records’]:
if record[‘eventName’] == ‘INSERT’:
new_image = record[‘dynamodb’][‘NewImage’]
user_email = new_image[‘Email’][‘S’]

# ... Extract any other necessary information ...

# Create an SES client
ses = boto3.client('ses')

# Send an email to the new subscriber
response = ses.send_email(
Source='majorkiema.mk@gmail.com', # Replace with your verified email address
Destination={
'ToAddresses': [user_email]
},
Message={
'Subject': {
'Data': 'Welcome to Our Service'
},
'Body': {
'Text': {
'Data': ' Thank you for filling out the form. Welcome to the Gold Grid family!'
}
}
}
)

print('Email sent successfully: ' + response['MessageId'])
Show less

Workflow for Lambda Code

  • Record insertion should trigger the lambda function.
  • The lambda function should parse the needed information from the event payload and compose email content.
  • Use the AWS SDK for Simple Email Service to send email notifications with the desired email subject, recipient(s) and email message.
  • Save your function.

Configure DynamoDB Stream

  • Navigate to the DynamoDB console and create a database and table to use if you don’t have existing ones.
  • Set the partition key (primary key) and optional sort key (use of this key will depend on your use case).
  • Select the table where you want to monitor new record insertions and navigate to Table settings.
  • Under Table settings, navigate to Exports and Streams and enable the stream feature. Choose the preferred stream view type. (The options are Key attributes only, New image, Old image and New and old image.)
  • In this case, we will use New image for our DynamoDB stream.
  • Copy the Amazon Resource Name (ARN) of the stream, as we will use it later.

Set Up the Lambda Function Trigger

There are two ways to do this:

Configure it in DynamoDB table settings under Exports and Streams, then scroll down to the Triggers section. Select Create a trigger and choose your AWS Lambda function. Set the batch size and remember to activate your trigger before clicking Create trigger.

Alternately, configure it in the AWS Lambda function interface:

Navigate to the AWS Lambda service and select your function code.

  • In the function overview page, select the Add a trigger button. Select a source. (Our use case is DynamoDB).
  • Select your table by typing your table name in the search bar or entering the ARN you copied from the previous step of configuring the DynamoDB Stream.
  • Ensure Activate trigger is checked.
  • Set the batch size and the starting position.
  • Leave everything as default and click the Add button to create your trigger.

Test and Deploy

  • Test the integration by inserting a new record into the DynamoDB table. Monitor the lambda function’s logs and check if the email notification is sent successfully.
  • If everything works as expected, deploy the lambda function to the desired environment (such as production).
  • If things did not work as expected, try to troubleshoot the errors by checking your lambda function logs and fixing the issue where possible.

Conclusion

That’s how you can use a lambda function to to call Amazon SES and send an email notice when a record is placed into the database using a DynamoDB record insertion event. You can also refer to the AWS documentation website for more on any processes you find challenging to understand.

Discover more insights into working with AWS in Andela’s blog post, “Deploy React on AWS Amplify Using Terraform.”

The post Configure Email Notifications With Amazon SES, Lambda and DynamoDB appeared first on The New Stack.

Leave a Reply