Task 5: Integrate Lambda with the powerful S3 service. Start by putting an object file in S3 that contains multiple email IDs. Then, utilizing the Boto3 library, retrieve those email IDs from the file. Take it a step further by leveraging the Boto3 library to send an email using the SES service for each email ID you retrieve.
3 min readJul 1, 2023
Creating a bucket my-emailer-bucket-test
Create a lambda function my-emailer-bucket-lambda-func
with permission of LambdaExecutionRole, LambdaS3ExecutionRole and AmazonSES
Add code to the lambda function
import json
import urllib.parse
import boto3
s3 = boto3.client('s3')
ses = boto3.client('ses')
def send_email(sender, recipient, subject, body):
response = ses.send_email(
Source=sender,
Destination={'ToAddresses': [recipient]},
Message={
'Subject': {'Data': subject},
'Body': {'Text': {'Data': body}}
}
)
print("Email sent! Message ID:", response['MessageId'])
def lambda_handler(event, context):
#print("Received event: " + json.dumps(event, indent=2))
# Get the object from the event and show its content type
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
try:
response = s3.get_object(Bucket=bucket, Key=key)
print("CONTENT TYPE: " + response['ContentType'])
file_content = response['Body'].read().decode('utf-8')
all_emails = file_content.split('\n')
all_emails = [each_email.strip(' \r\n\t') for each_email in all_emails]
all_emails = [each_email for each_email in all_emails if len(each_email)]
# Do something with the file content
print(f"FILE CONTENT: {all_emails}")
for each_email in all_emails:
send_email('deepaksinghgs30@gmail.com', each_email, "Test subject", "Hello from deepaksingh")
return response['ContentType']
except Exception as e:
print(e)
print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
raise e
Create a verified identity in Amazon SES Service so that you can send and receive email
All configuration done.
Upload file to S3 to check if trigger happens or not on file upload.
Cloudwatch monitor
Mail sent
Done.
Here we learnt how to send email to all the email id contained in a text file using Amazon SES service.