尝试使用AWS ESS发送电子邮件并将zip文件作为附件附加

时间:2019-06-02 00:04:50

标签: python boto3

我正在尝试使用存储在aws s3中的zip文件作为使用aws ses发送的电子邮件的附件。

我的想法是从s3获取zip文件并读取它,然后传递给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)
)

当我这样做时,我在MIMEApplication行中收到“ ValueError:嵌入式空字节”。为什么是这样?如何解决? 任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

使用上述步骤解决。代码示例:

#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()
ses send_raw_email()代码的

doc示例: https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-raw.html#send-email-raw-headers