Search code examples
pythonamazon-web-servicesamazon-s3aws-lambdaemail-attachments

How to make a Python AWS Lambda open an email stored in S3 as email object


I realize this is a total noob question and hopefully an easy solution exists. However, I'm stuck and turning to you for help! What I'm trying to do is this: I have an SES rule set that stores emails in my S3 bucket. The specific emails I'm storing contain a .txt attachment. I'm hoping to have a Lambda function that is triggered on S3 bucket "Create" function, open the email AND attachment, and then perform some other processing based on specific text in the email attachment.

My specific question is this: How do I allow the Lambda function to take the S3 email "object" and convert it to the standard Python "message" object format so that I can use Python's Email library against it?

Here is what I have so far...not much, I know:

import boto3
import email

def lambda_handler(event, context):
s3 = boto3.client("s3")

if event: 

    print("My Event is : ", event)
    file_obj = event["Records"][0]
    filename = str(file_obj["s3"]['object']['key'])
    print("filename: ", filename)
    fileObj = s3.get_object(Bucket = "mytestbucket", Key=filename)
    print("file has been gotten!")

    #Now that the .eml file that was stored in S3 is stored in fileObj, 
    #start parsing it--but how to convert it to "email" class???
    #??????

Solution

  • Can you try something like this?. With this, you will get msg object back from stream you opened with S3 file.

    import boto3
    import email
    
    def lambda_handler(event, context):
    s3 = boto3.client("s3")
    
    if event: 
    
        print("My Event is : ", event)
        file_obj = event["Records"][0]
        filename = str(file_obj["s3"]['object']['key'])
        print("filename: ", filename)
        fileObj = s3.get_object(Bucket = "mytestbucket", Key=filename)
        print("file has been gotten!")
        msg = email.message_from_bytes(fileObj['Body'].read())
        print(msg['Subject'])
        #Hello