Skip to main content

Command Palette

Search for a command to run...

Building Scalable Email Automation with AWS Lambda, SES, and S3

A Comprehensive Guide to Mass Emailing Using Serverless Architecture

Updated
4 min read
Building Scalable Email Automation with AWS Lambda, SES, and S3
A
Cloud & DevOps Engineer and Python Developer with expertise in Kubernetes (GKE/EKS), CI/CD automation, and infrastructure optimization. Experienced in developing web applications using Python, Django, FastAPI, and modern cloud architectures that deliver measurable business impact. Backed by multiple industry certifications including Google Cloud Professional Cloud Architect, Developer and DevOps Engineer, AWS Solutions Architect - Associate, and Google Cloud Digital Leader. Published IEEE paper on AI-based rainfall prediction and contributed to open-source projects including SeaweedFS.

Welcome, fellow cloud maestros! In this blog post, we'll dive into the exciting world of mass emailing using AWS Lambda, Simple Email Service (SES), and Simple Storage Service (S3). By the end of this project, you'll have a hands-on understanding of serverless functions, cloud storage, and email automation, showcasing your ability to create cost-effective and scalable solutions.

Introduction

Email marketing is a powerful tool for businesses to engage with their audience. However, sending personalized emails to a large audience can be a daunting task. That's where AWS Lambda, SES, and S3 come into play. In this project, I'll walk you through the process of setting up a serverless function that automates the mass emailing process, making it not only efficient but also scalable.

1. Setting Up S3 for CSV File Uploads

Create a designated S3 bucket where you'll upload a CSV file containing email addresses and message content.

2. Creating and Verifying SES Identities

Before diving into the email-sending process, create SES identities for both sender and receiver email addresses. This involves verifying domain ownership and email address verification within the SES console. These identities are essential for maintaining a high deliverability rate and ensuring that your emails reach the intended recipients.

firstpirateking.onepiece@gmail.com is the sender's email address, and all other email addresses are considered receiver email addresses.

When setting up SES identities, you would verify the email address for firstpirateking.onepiece@gmail.com as the sender, and for other email addresses, you would ensure their verification within the SES console to maintain a high deliverability rate. This distinction is essential for configuring SES to handle both the sender and receiver roles effectively in your mass email automation project.

3. Setting Up AWS Lambda with SES

Create an AWS Lambda function and configure it to access SES. Ensure that your Lambda function has the necessary permissions to send emails through SES. This step is crucial for establishing a secure and reliable connection between your Lambda function and the email service.

3.1 Create a role for Lambda

To empower your Lambda function, create an IAM (Identity and Access Management) role that grants the required permissions.

Attach Policies: In the "Attach permissions policies" section, search for and attach the following policies:

  • AmazonS3ReadOnlyAccess

  • AmazonSESFullAccess

  • CloudWatchLogsFullAccess

These policies grant the Lambda function read access to S3, full access to SES, and full access to CloudWatch Logs for monitoring purposes.

3.2 Create a Lambda Function

With the IAM role in place, it's time to create the Lambda function. This function will be responsible for handling the logic of your mass email campaign.

4. Setting S3 Event Triggers

To make the process seamless, configure an S3 event trigger that monitors the designated bucket for new CSV file uploads. Whenever a new file is detected, this trigger will automatically invoke your Lambda function, initiating the email-sending process.

5. Logic for Lambda Function

Develop a robust logic within your Lambda function to import the CSV file, extract recipient information, and send personalized messages using AWS SES. This step involves parsing the CSV file, extracting relevant data, and dynamically generating personalized emails for each recipient.

After writing the code, click Deploy

import json
import boto3
import urllib.parse
import csv
from io import StringIO

ses = boto3.client('ses', region_name='ap-south-1')
s3 = boto3.client('s3')

def lambda_handler(event, context):

    s3_bucket_name = event['Records'][0]['s3']['bucket']['name']
    s3_file_key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')

    print(s3_bucket_name)
    print(s3_file_key)

    ses_sender_email = 'firstpirateking.onepiece@gmail.com'

    response = s3.get_object(Bucket=s3_bucket_name, Key=s3_file_key)
    csv_data = response['Body'].read().decode('utf-8')
    reader = csv.DictReader(csv_data.splitlines())
    for row in reader:
            recipient_email = row['Email']
            personalized_message = row['Message']

            # print(recipient_email)
            # print(personalized_message)

            send_email(ses, ses_sender_email, recipient_email, personalized_message)

def send_email(ses, sender_email, recipient_email, message):
    ses.send_email(
        Source = sender_email,
        Destination = {
            'ToAddresses': [recipient_email]
        },
        Message = {
            'Subject': {
                'Data': 'Testing SES',
                'Charset': 'UTF-8'
            },
            'Body': {
                'Text':{
                    'Data': message,
                    'Charset': 'UTF-8'
                }
            }
        }
    )

    return {
        'statusCode': 200,
        'body': json.dumps('Successfully sent email from Lambda using Amazon SES')
    }

6. Upload CSV File

It's time to populate it with your CSV files. Ensure that each file contains crucial information, including recipient email addresses and personalized message content. This step forms the foundation for your mass emailing campaign.

one piece.csv

Once the CSV file is successfully uploaded into the designated S3 bucket, the magic begins. The configured S3 event trigger promptly notifies the SESLambdaFunction Lambda function of the new file's presence. This trigger initiates the Lambda function, which, in turn, reads the CSV file, extracts recipient information, and dynamically generates personalized emails. Now, watch as your meticulously crafted emails are sent to the specified email addresses within the CSV file, demonstrating the power of serverless architecture in automating mass email campaigns efficiently.

Conclusion

By completing these steps, you've showcased your ability to integrate serverless functions, cloud storage, and email automation – a valuable addition to your skill set and a testament to your capability in the evolving landscape of cloud technology. Whether you're a seasoned developer or a newcomer, this project paves the way for a successful and impactful career in the tech industry.

B

TROPICAL DELIGHT RECOVERY IS THE ONLY VERIFIED LICENSE COMPANY.

Are you looking for a way to recover cryptocurrency you misplaced or had stolen? I'm pleased to inform that Tropical Delight Recovery Hacker has resolved the issue that nearly caused my house to fall since I spent the monies my spouse wanted to utilise to start a business. I lost $1.4 million in bitcoin and etherium to these scammers. They excel at what they do and are the leading certified cryptocurrency recovery company. They can be reached instantly at: @ tropicaldelightrecoveryhacker on Telegram and @ tropicaldelightrecoveryhacker.93 on Signal. The email address is TropicalDelightRecoveryHacker @ out look .com.

M
Myla Juun2y ago

Congratulation! @ slope game

R

Very well put together article mate can you explain how though how could we send mails to unverified email IDs and domains?

1
A

Amazon SES imposes certain restrictions on sending emails to unverified addresses and domains to prevent abuse and maintain high deliverability rates.

By default, when you first start using Amazon SES, your account is in the SES sandbox. In sandbox mode, you're only allowed to send emails to verified email addresses and domains. This is a precautionary measure to prevent misuse of the service.

To send emails to unverified addresses and domains, you need to move out of the sandbox. This involves requesting production access for your SES account. Once approved, you'll be able to send emails to any recipient, verified or unverified. However, moving out of the sandbox requires a thorough review of your SES usage and adherence to Amazon's policies.

3
C

Informative 👏Aniket Dubey

1
P

Absolutely love how this blog walks you through the entire process, from setting up S3 to creating SES identities and mastering Lambda functions. The screenshots and code snippets make it so much easier to understand and apply. A must-read for anyone diving into email automation with AWS!

14

More from this blog

A

Aniket Dubey

7 posts

My passion lies in creating scalable serverless solutions in AWS. I thrive on crafting efficient Infrastructure as Code(IaC) using Terraform.