Receive and Parse Emails on AWS SES
<p>I want to setup a Lambda function to parse incoming emails to SES. I followed the documentation and setup the receipt rules. </p>

<p>I tested out my script by storing a MIME email in a txt file, parsing the email, and storing required info in a JSON document to be stored in a database. Now, I'm unsure of how to access the received email from SES and pull the information into my Python script. Any help would be greatly appreciated. </p>

<pre><code>from email.parser import Parser
parser = Parser()

f = open('roundtripMime.txt', "r")
rawText = f.read()
incoming = Parser().parsestr(rawText)

subject = incoming
subjectList = subject.split("|")

#Get number
NumberList = subjectList[0].split()
Number = NumberList[2].strip("()")

#Get Name
fullNameList = subjectList[3].split("/")
firstName = fullNameList[1].strip()
lastName = fullNameList[0].strip()
</code></pre>

<p>You can set up an Action in your SES Rules Set to automatically PUT your email files into S3. Then you set up an event in S3 (for a specific bucket) to trigger your lambda function. With that, you will be able to retrieve the email with something like this:</p>

<pre><code>def lambda_handler(event, context):

    for record in event['Records']:
        key = record['s3']['object']['key']
        bucket = record['s3']['bucket']['name'] 
        # here you can download the file from s3 with bucket and key
</code></pre>

python aws-lambda amazon-ses