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

not*_*peg 2 python email mime smtp

我不能发送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)
Run Code Online (Sandbox Code Playgroud)

我需要使用一个,Multipart所以我也可以添加附件,但为了简单起见我保留了代码.

Mar*_*ers 5

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

msg = MIMEMultipart('alternative')
Run Code Online (Sandbox Code Playgroud)

默认是mixed; 查看电子邮件库示例.

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