AWS Lambda to Send an Email when File uploaded in S3 bucket

AWS Lambda to Send an Email when File uploaded in S3 bucket

get an Email notification when ever a file is uploaded in S3 bucket
refer the steps mentioned below

Prerequisites:

  1. AWS Account: need an AWS account [free tier is enough to practice this task] to create and manage Lambda functions, S3 buckets, and SES (Simple Email Service) for sending emails.

  2. Permissions: Ensure your Lambda function has permissions to read from the S3 bucket and send emails using SES. This can be configured through IAM roles.

Implementation Steps:

1. Create a S3 bucket and configure S3 Event Trigger for Lambda

If you want the Lambda function to trigger automatically when a file is uploaded to S3, you can set up an S3 event trigger:

  • Go to the Amazon S3 console.

  • Navigate to your bucket.

  • Choose "Properties" > "Events" > "Create event notification".

  • Configure the event notification to trigger the Lambda function when a new object is created.

2. Write the Lambda Function Code

Lambda function (lambda_to_send_email.py):

import os
import boto3
from botocore.exceptions import ClientError
import logging
import json
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import smtplib

# Configure logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)

# Initialize S3 and SES clients
s3_client = boto3.client('s3')
ses_client = boto3.client('ses')

def lambda_handler(event, context):
    # Get the bucket and object key from the S3 event notification
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = event['Records'][0]['s3']['object']['key']

    # Temporarily download the file to Lambda's /tmp directory
    download_path = '/tmp/{}'.format(os.path.basename(key))
    s3_client.download_file(bucket, key, download_path)

    # Email parameters
    sender = 'sender@example.com'
    recipient = 'recipient@example.com'
    subject = 'File from S3 Bucket'
    body_text = 'Please find the attached file from S3.'

    # Create a MIME multipart message
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = recipient
    msg.attach(MIMEText(body_text))

    # Attach the file to the email
    attachment = MIMEApplication(open(download_path, 'rb').read())
    attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(download_path))
    msg.attach(attachment)

    # Send the email
    try:
        response = ses_client.send_raw_email(
            Source=sender,
            Destinations=[recipient],
            RawMessage={'Data': msg.as_string()}
        )
        logger.info("Email sent successfully: {}".format(response['MessageId']))
    except ClientError as e:
        logger.error("Error sending email: {}".format(e.response['Error']['Message']))
        raise

    # Clean up: Delete the downloaded file from /tmp
    os.remove(download_path)

3. Configure Lambda Function

  • Go to the AWS Lambda console.

  • Click on "Create function".

  • Choose "Author from scratch".

  • Configure the function:

    • Name: Enter a name for your Lambda function.

    • Runtime: Select Python (choose a version supported by your code).

    • Execution role: Create a new role with basic Lambda permissions.

  • Upload your (lambda_to_send_email.py) code as the function code.

4. Set Environment Variables (Optional)

You can set environment variables in Lambda to store sensitive information like SMTP credentials or SES configuration details.

5. Set up SES (Simple Email Service)

Ensure your SES service is set up to send emails. You may need to verify sender and recipient email addresses in the SES console.

6. Test Your Lambda Function

  • Upload a file to your S3 bucket and verify if the Lambda function triggers and sends the email successfully.

7. Monitor and Troubleshoot

Monitor Lambda logs in CloudWatch for any errors or unexpected behavior during execution.

Notes:

  • Security: Ensure your Lambda function has appropriate IAM permissions to access S3 and SES.

  • Error Handling: Implement error handling to manage exceptions during S3 download and email sending.

  • Attachments: Lambda has /tmp directory with limited storage (512MB). Ensure your attachments fit within this limit.

  • Cost: Monitor Lambda invocations and data transfer costs associated with S3 and SES usage.

By following these steps, you can create a Lambda function that retrieves a file from an S3 bucket and sends it via email using SES in response to an event trigger (like an S3 upload).