Step-by-Step Guide to Automating Email Attachments via AWS Lambda and S3 Uploads"
Learn how to trigger AWS Lambda from S3 uploads and send file attachments using Amazon SES
Here is how you can automate email sending using Lambda, S3 and SES.
Before I dive into the steps, here are definitons of each the AWS servies to get some context:
Lambda Function: A serverless compute service that runs code in response to events without provisioning or managing servers.
SES (Simple Email Service): A scalable email sending service to send transactional, marketing, or notification emails.
S3 (Simple Storage Service): An object storage service to store and retrieve data like files, images, and backups.
IAM (Identity and Access Management): A service that controls user access and permissions to AWS resources.
CloudWatch Logs: A service that monitors and logs activity for AWS resources, including Lambda functions, to troubleshoot and analyze performance.
The deployment steps using the resources mentioned above are as follows:
1. Create the Lambda Function
Go to Lambda Console:
In the AWS Management Console, navigate to Lambda and click Create function.
Configure the Lambda Function:
Function name: e.g.,
SendEmailWithAttachment
.Runtime: Choose Python or Node.js (depending on your preference).
Permissions: Choose or create a new role with permissions for SES and S3 access.
Lambda Function Code (Python Example): Here's a simple example that attaches the S3 file to an email and sends it via SES.
import boto3
import base64
import json
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
# Initialize clients
s3 = boto3.client('s3')
ses = boto3.client('ses')
def lambda_handler(event, context):
# Get S3 bucket and object key from the event
bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
# Get the object from S3
s3_object = s3.get_object(Bucket=bucket, Key=key)
file_data = s3_object['Body'].read()
# Create email message with attachment
msg = MIMEMultipart()
msg['From'] = 'your-email@example.com'
msg['To'] = 'recipient@example.com'
msg['Subject'] = f"File Upload: {key}"
# Attach the file
part = MIMEBase('application', 'octet-stream')
part.set_payload(file_data)
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename={key}')
msg.attach(part)
# Send email via SES
try:
response = ses.send_raw_email(
Source='your-email@example.com',
Destinations=['recipient@example.com'],
RawMessage={'Data': msg.as_string()}
)
return response
except Exception as e:
print(f"Error sending email: {str(e)}")
raise e
Deploy the Lambda Function: Click Deploy to save and deploy the function.
2. Set Up S3 Event Notification to Trigger Lambda
Go to S3 Console:
Navigate to S3 and select the bucket where files will be uploaded.
Configure Event Notification:
Go to the Properties tab of the bucket.
Scroll down to Event notifications and click Create event notification.
Specify Trigger Settings:
Event name: e.g.,
FileUploadTrigger
.Event types: Select
PUT
for object uploads.Prefix/Suffix: Optionally specify a prefix (e.g.,
uploads/
) or suffix (e.g.,.jpg
) to filter files.Destination: Choose Lambda function and select the Lambda function you created (
SendEmailWithAttachment
).
Save the Event Notification:
Click Save changes to finalize the event notification.
3. Set Permissions for Lambda
IAM Role Permissions:
Ensure the IAM role associated with the Lambda function has permissions for SES and S3 access.
Lambda Role Policy (Example):
Add the following policies to your Lambda's execution role:
S3 Permissions (Example):
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::your-bucket-name/*" } ] }
SES Permissions(Example):
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "ses:SendRawEmail", "Resource": "*" } ] }
Grant Permission for S3 to Trigger Lambda:
Go to the Lambda function > Configuration > Triggers.
Click on Add trigger and select your S3 bucket. Confirm the event type is
PUT
.Click Add.
4. Test the Setup
Upload a File to S3:
Upload a file to the S3 bucket. This should trigger the Lambda function.
Monitor Lambda Execution:
Go to CloudWatch Logs to check the logs of the Lambda function for any errors or successful execution.
Check Email:
Check the recipient's inbox to confirm the email with the file attachment has been sent via SES.
This series of steps should help you set up an AWS Lambda function that gets triggered by S3 uploads, which sends the uploaded file as an attachment via SES. Be sure to adjust IAM policies, Lambda code, and S3 event configurations to match your specific requirements!