Python使用正文内容通过电子邮件发送Multipart

时间:2012-08-16 21:29:57

标签: python email smtp mime

我无法使用正文作为多部分电子邮件在python中发送电子邮件。我尝试的所有内容都将所有内容都作为附件,我无法将文本或html显示在正文中。

msg = MIMEMultipart()
if msg_mime_type == 'text' or not msg_mime_type:
    new_body = MIMEText(body, 'text')
elif msg_mime_type == 'image':
    new_body = MIMEImage(body)
elif msg_mime_type == 'html':
    new_body = MIMEText(body, 'html')
new_body.add_header('Content-Disposition', 'inline', filename='body')
msg.set_payload(new_body) #also tried msg.attach(new_body)

我需要使用Multipart以便我也可以添加附件,但为了简单起见,我保留了这些代码。

1 个答案:

答案 0 :(得分:5)

您需要指定这些部件是彼此的替代品,例如multipart/alternative mime类型:

msg = MIMEMultipart('alternative')

默认为mixed;请参阅email library examples

请注意,要创建包含附件和备用(HTML / CSS)选项的电子邮件,您需要将包含multipart/related部分的顶级alternative容器作为第一个条目