Skip to content

Instantly share code, notes, and snippets.

@mmansoor
Created June 9, 2022 13:46
Show Gist options
  • Save mmansoor/ac71e76b475511182f2c99ceec44816c to your computer and use it in GitHub Desktop.
Save mmansoor/ac71e76b475511182f2c99ceec44816c to your computer and use it in GitHub Desktop.
Read Email from S3
import json
import boto3
from email.parser import BytesParser
from email import policy
import os
def lambda_handler(event, context):
message = event['Records'][0]['Sns']['Message']
print(type(message))
data = json.loads(message)
print(type(data))
receipt = data['receipt']
print(type(receipt))
#print(receipt)
bucket_name = receipt['action']['bucketName']
print(bucket_name)
object_key = receipt['action']['objectKey']
print(object_key)
s3 = boto3.client('s3')
obj = s3.get_object(Bucket=bucket_name, Key=object_key)
print(obj)
raw_email = obj['Body'].read()
msg = BytesParser(policy=policy.SMTP).parsebytes(raw_email)
# get the plain text version of the email
plain = ''
try:
plain = msg.get_body(preferencelist=('plain'))
plain = ''.join(plain.get_content().splitlines(keepends=True))
plain = '' if plain == None else plain
except:
print('Incoming message does not have an plain text part - skipping this part.')
print(plain)
# get the HTML version of the email
html = ''
try:
html = msg.get_body(preferencelist=('html'))
html = ''.join(html.get_content().splitlines(keepends=True))
html = '' if html == None else html
except:
print('Incoming message does not have an HTML part - skipping this part.')
print(html)
# TODO implement
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment