How to save WorkMail email attachment to tmp location and push to s3 in lambda using python

269 Views Asked by At

I want to push my email attachment to s3 bucket using python, my following piece of code doing that task but when new email hits with different file name this is not working.

I want to upload any dynamic name and extension to the s3 bucket.

I am new bee in python.

Thanks in advance.

# Write the attachment to a temp location
    open('/tmp/filename.csv', 'wb').write(attachment.get_payload(decode=True))
1

There are 1 best solutions below

0
Rene B. On

You can use the following code to extract the attachment from the lambda:

def get_attachment(msg, content_type):
"""
Moves through a tree of email Messages to find an attachment.
:param msg: An email Message object containing an attachment in its Message tree
:param content_type: The type of attachment that is being searched for
:return: An email Message object containing base64 encoded contents (i.e. the attachment)
"""
attachment = None
msg_content_type = msg.get_content_type()

if ((msg_content_type == content_type or msg_content_type == 'text/plain')
        and is_base64(msg.get_payload())):
    attachment = msg

elif msg_content_type.startswith('multipart/'):
    for part in msg.get_payload():
        attachment = get_attachment(part, content_type)
        attachment_content_type = attachment.get_content_type()

        if (attachment and (attachment_content_type == content_type
                            or attachment_content_type == 'text/plain')
                and is_base64(attachment.get_payload())):
            break
        else:
            attachment = None

return attachment

Its described here: https://medium.com/caspertechteam/processing-email-attachments-with-aws-a35a1411a0c4