Created
July 2, 2018 13:58
-
-
Save nilasissen/c73c4ac6bca15ee8ea6e0490ca868076 to your computer and use it in GitHub Desktop.
AWS ses email file extractor . you can extract the attachment from email using this code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import email | |
import zipfile | |
import os | |
import gzip | |
import string | |
import boto3 | |
import urllib | |
import json | |
from botocore.vendored import requests | |
from email.mime.text import MIMEText | |
import pprint | |
import collections | |
print('Lamda function running...') | |
def lambda_handler(event, context): | |
data = json.loads(event['Records'][0]['Sns']['Message']) | |
try: | |
# test2 | |
# test1 | |
# Read the raw text file into a Email Object | |
msg = email.message_from_string(data['content']) | |
if len(msg.get_payload()) > 0: | |
url = 'http://abc.com/urApi' | |
# The first attachment | |
# attachment = msg.get_payload()[1] | |
# print(attachment.get_payload()) | |
# print(msg.get_payload()) | |
file_A = [] | |
for file in msg.get_payload(): | |
if msg.get_payload().index(file)!=0: | |
contentdisp = str.split(file.get('Content-Disposition'),'=') | |
fname = contentdisp[1].replace('\"', '') | |
file_A.append({"filename":fname,"base64":file.get_payload()}) | |
# print(file_A) | |
data_json = { | |
"subject": msg['Subject'], | |
"to": msg['To'], | |
"from": data['mail']['source'], | |
"reply":data['content'] | |
} | |
if len(msg.get_payload()) > 1: | |
data_json['files'] = json.dumps(file_A) | |
headers ={'Content-Type':'application/x-www-form-urlencoded'} | |
res = requests.post(url, data=data_json, headers=headers) | |
# print(res) | |
print(res.content) | |
except Exception as e: | |
raise e | |
# print("Could not see file/attachment.") | |
# {}. Make sure they exist ' | |
#'and your bucket is in the same region as this ' | |
#'function.'.format(key, bucket)) | |
# delete_file(key, bucket) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment