Skip to content

Instantly share code, notes, and snippets.

@Burekasim
Created November 22, 2022 19:27
Show Gist options
  • Save Burekasim/d48409ccd2b203904c75394a7bc5e834 to your computer and use it in GitHub Desktop.
Save Burekasim/d48409ccd2b203904c75394a7bc5e834 to your computer and use it in GitHub Desktop.
Ses to sns to lambda to s3
import boto3
import json
from datetime import datetime
import email
from email import policy
def print_with_timestamp(*args):
print(datetime.utcnow().isoformat(), *args)
def upload_to_s3(file_name, body):
s3 = boto3.resource('s3')
s3_bucket = 'BUCKET_NAME'
s3_file_name = f'{file_name}.txt'
#s3.Bucket(s3_bucket).put_object(Key=s3_file_name, Body=body, ACL='public-read')
s3.Bucket(s3_bucket).put_object(Key=s3_file_name, Body=body)
return {
"statusCode": 200,
"body": json.dumps('File ' + s3_file_name + 'Has successfuly uploaded to bucket: ' + s3_bucket)
}
def lambda_handler(event, context):
print_with_timestamp('Starting - email 2 s3')
dict_to_s3 = {}
# Extract data from email
email_json = json.loads(event['Records'][0]['Sns']['Message'])
receipt = email_json['mail']['destination'][0]
from_address = email_json['mail']['commonHeaders']['from'][0]
subject = email_json['mail']['commonHeaders']['subject']
parse_email = email.message_from_string(email_json['content'], policy=policy.default)
# variables to dict
dict_to_s3['email_body'] = str(parse_email.get_body())
dict_to_s3['to'] = str(receipt)
dict_to_s3['subject'] = subject
dict_to_s3['from'] = str(email_json['mail']['commonHeaders']['from'][0])
print_with_timestamp('Processing email from:', from_address)
# for recipient in receipt['recipients']:
upload_to_s3(receipt, json.dumps(dict_to_s3))
try:
return {'disposition': 'stop_rule_set'}
except Exception as e:
print_with_timestamp(e)
print_with_timestamp('An error occurred while sending bounce for message: ')
raise e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment