2

I am trying to use a zip file stored in aws s3 as an attachment in an email sent using aws ses.

The idea i have is GET the zipfile from s3 read it and pass to boto3 send_raw_email() api.

zip_response = s3_client.get_object(
    Bucket='bucket name',
    Key='access_key.zip'
    )
zip_streambody = zip_response['Body'].read()

#adding the attachment for send_raw_email() operation
'Define attachment and encode using mime app'
att = MIMEApplication(open(ATTACHMENT, 'rb').read())

'header to tell email client to treat it as attachment and give it a name'
att.add_header(
    'Content-Disposition', 
    'attachment',
    filename=os.path.basename(ATTACHMENT)
)

When i do this i get a "ValueError: embedded null byte" in the MIMEApplication line. Why is this? How to fix it? Any help is appreciated.

  • https://stackoverflow.com/questions/10474650/how-to-send-a-zip-file-as-an-attachment-in-python – John Hanley Jun 02 '19 at 02:39
  • Thanks for the help, this didn't work for me as the file is in s3 and i am using Lambda as my runtime. What worked was zipping the streaming body i got from s3 and storing it in the lambda /tmp space and then using it. – Ankit Thakur Jun 02 '19 at 10:48
  • Post your new code as an answer. – John Hanley Jun 02 '19 at 15:53

1 Answers1

0

Solved using the procedure mentioned above. Code example:

#main module
zip_response = s3_client.get_object(
    Bucket='bucket name',
    Key='access_key.zip'
    )
zip_streambody = zip_response['Body'].read()
call_function_in_module2(zip_streambody)

#module 2

call_function_in_module2(x)
#write the streambody beginning with correct zip headers, save zip as follows,
#give path to lambda temp storage, /tmp/zip_name.zip. Save path to var, ATTACHMENT  
with open('/tmp/my_key.zip', 'wb') as file:
        file.write(x)

#adding the attachment for send_raw_email() operation
'Define attachment and encode using mime app'
att = MIMEApplication(open(ATTACHMENT, 'rb').read())

'header to tell email client to treat it as attachment and give it a name'
att.add_header(
    'Content-Disposition', 
    'attachment',
    filename=os.path.basename(ATTACHMENT)
)

send_raw_email()

doc for ses send_raw_email() code example: https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-raw.html#send-email-raw-headers