pythonboto3

Trying to send email using aws ses and attach zip file as attachment


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.


Solution

  • 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