Boto SES - send_raw_email()给多个收件人

时间:2015-04-15 20:34:40

标签: python email mime-types boto amazon-ses

我在这个问题上遇到了很大的时间问题 - 另一个关于SO的问题没有解决问题的地方在这里:Send Raw Email (with attachment) to Multiple Recipients

我的代码(有效)很简单:

def send_amazon_email_with_attachment(html, subject, now, pre):
    dummy = 'test@example.com'
    recipients = ['test1@exampl.ecom', 'test2@example.com', 'test3@example.com']
    connS3 = S3Connection('IDENTIFICATION','PASSWORD')
    b = connS3.get_bucket('BUCKET_NAME')
    key = b.get_key('FILE_NAME.pdf')
    temp = key.get_contents_as_string()

    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = 'My Name <test@example.com>'        

    msg.preamble = 'Multipart message.\n'

    part1 = MIMEText(u"Attached is the report", 'plain')
    part2 = MIMEText(html, 'html')

    msg.attach(part1)
    msg.attach(part2)

    part = MIMEApplication(temp) #read binary
    part.add_header('Content-Disposition', 'attachment', filename='FILE_NAME.pdf')
    msg.attach(part)

    conn = boto.ses.connect_to_region('us-east-1', aws_access_key_id='AUTH_ID', aws_secret_access_key='AUTH_PW')
    for recipient in recipients:
        print recipient
        msg['To'] = recipient

        result = conn.send_raw_email(msg.as_string(), source=msg['From'], destinations=recipient)

但是,有一个警告......这是为每个收件人循环。此的任何变体都不起作用。将列表传递到msg['Bcc']msg['BCC']将返回错误,该列表无法被删除(与发布的问题相同的错误)。传递用逗号分隔的字符串会产生亚马逊SES问题,说“非法电子邮件”和“非法电子邮件”。在返回的XML中。因为我在特定情况下只收到来自亚马逊的错误,所以我在相应的API调用之前认为这是程序错误。

任何MIMEMultipart专家都有一些想法吗?

1 个答案:

答案 0 :(得分:12)

基本上,您需要使用2种不同的格式在2个不同的地方指定电子邮件收件人。

def send_amazon_email_with_attachment(html, subject, now, pre):
    dummy = 'test@example.com'
    recipients = ['test1@exampl.ecom', 'test2@example.com', 'test3@example.com']
    connS3 = S3Connection('IDENTIFICATION','PASSWORD')
    b = connS3.get_bucket('BUCKET_NAME')
    key = b.get_key('FILE_NAME.pdf')
    temp = key.get_contents_as_string()

    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = 'My Name <test@example.com>' 
    msg['To'] = ', '.join(recipients)


    msg.preamble = 'Multipart message.\n'

    part1 = MIMEText(u"Attached is the report", 'plain')
    part2 = MIMEText(html, 'html')

    msg.attach(part1)
    msg.attach(part2)

    part = MIMEApplication(temp) #read binary
    part.add_header('Content-Disposition', 'attachment', filename='FILE_NAME.pdf')
    msg.attach(part)

    conn = boto.ses.connect_to_region('us-east-1', aws_access_key_id='AUTH_ID', aws_secret_access_key='AUTH_PW')


    result = conn.send_raw_email(msg.as_string(), source=msg['From'], destinations=recipients)