import os.path import boto3 import gzip import shutil from botocore.exceptions import ClientError from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication s3 = boto3.client("s3") def lambda_handler(event, context): mail_sender = "abc@abc.com" mail_recipient = "efg@efg.com" aws_region = "ap-east-1" mail_subject = "Monthly billing csv 410429265162" FILEOBJ = event["Records"][0] BUCKET_NAME = str(FILEOBJ['s3']['bucket']['name']) KEY = str(FILEOBJ['s3']['object']['key']) FILE_NAME = os.path.basename(KEY) temp_file = '/tmp/' + FILE_NAME s3.download_file(BUCKET_NAME, KEY, temp_file) with open(temp_file, 'rb') as f_in: with gzip.open('billing-csv.gz', 'wb') as f_out: shutil.copyfileobj(f_in, f_out) ATTACHMENT = '/tmp/billing-csv.gz' BODY_TEXT = "The Object file was uploaded to S3" client = boto3.client('ses',region_name=aws_region) msg = MIMEMultipart() # Add subject, from and to lines. msg['Subject'] = mail_subject msg['From'] = mail_sender msg['To'] = mail_recipient textpart = MIMEText(BODY_TEXT) msg.attach(textpart) att = MIMEApplication(open(ATTACHMENT, 'rb').read()) att.add_header('Content-Disposition','attachment',filename=ATTACHMENT) msg.attach(att) print(msg) try: response = client.send_raw_email( Source=mail_sender, Destinations=[mail_sender,mail_recipient], RawMessage={ 'Data':msg.as_string() } ) except ClientError as e: print(e.response['Error']['Message']) else: print("Email sent! Message ID:",response['MessageId'])