如何在 python 2 中向多部分电子邮件添加正文?
Posted
技术标签:
【中文标题】如何在 python 2 中向多部分电子邮件添加正文?【英文标题】:How to add a body text to a multipart email in python 2? 【发布时间】:2017-03-11 01:34:00 【问题描述】:我正在使用 python 2 成功发送带有附件的邮件。但是邮件仍然没有正文内容。
谁能告诉我如何添加正文以及附件和主题。
我当前的代码是:
import smtplib, os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders
from email.mime.text import MIMEText
SUBJECT = "Email Data"
emaillist=['xyz@hotmail.com']
msg = MIMEMultipart('mixed')
msg['Subject'] = 'SUBJECT '
msg['From'] = 'abc@gmail.com'
msg['To'] = ', '.join(emaillist)
part = MIMEBase('application', "octet-stream")
part.set_payload(open('C:'+os.sep+'Desktop'+os.sep+'temp1.txt', `"rb").read())`
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="output.txt"')
msg.attach(part)
server = smtplib.SMTP("smtp.gmail.com",587)
server.ehlo()
server.starttls()
server.login("abc@gmail.com", "password")
server.sendmail(msg['From'], emaillist , msg.as_string())
【问题讨论】:
【参考方案1】:来自https://docs.python.org/2/library/email-examples.html:
text = "Here is the message body"
html = """
<html>
<head></head>
<body>
<p>here is some html<br>
Here is some link <a href="https://www.python.org">link</a>.
</p>
</body>
</html>
"""
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
在msg.attach(part)
之后插入这个
【讨论】:
我试过了,它抛出了这个错误:** 'Cannot attach additional subparts to non-multipart/*') email.errors.MultipartConversionError: Cannot attach additional subparts to non-multipart/* * * 好的,我没有完全理解你的问题。更新了答案。以上是关于如何在 python 2 中向多部分电子邮件添加正文?的主要内容,如果未能解决你的问题,请参考以下文章