[英]Python-sent MIME email attachments not showing up in some clients
我正在發送帶有 python 腳本的 email。 這是一封由純文本 html 和一個附件組成的多部分郵件。
郵件已正確發送,但在某些客戶端上未顯示附件。 我在這個討論中讀到通過“html”或“混合”更改“替代”解決了問題message = MIMEMultipart("alternative")
但從那以后,部分純文本和 html 都出現在郵件正文中。 如何解決這個問題?
謝謝
# Create a multipart message and set headers
message = MIMEMultipart("mixed")
message["From"] = sender_email
message["To"] = ", ".join(to)
message["Cc"] = ", ".join(cc)
message["Subject"] = subject
filename = 'myfile.zip'
mimetype, encoding = guess_type(os.path.join(os.path.abspath(savepath),filename))
mimetype = mimetype.split('/', 1)
fp = open(os.path.join(os.path.abspath(savepath),filename), 'rb')
attachment = MIMEBase(mimetype[0], mimetype[1])
attachment.set_payload(fp.read())
# Encode file in ASCII characters to send by email
encoders.encode_base64(attachment)
# Add header as key/value pair to attachment part
attachment.add_header('Content-Disposition','attachment', filename=filename)
# Create the plain-text and HTML version of your message
text = """\
my plain-text body
"""
html = """\
<html> my html body</html>
"""
# Add attachment to message and convert message to string
message.attach(attachment)
# Turn these into plain/html MIMEText objects
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
# Add HTML/plain-text parts to MIMEMultipart message
# The email client will try to render the last part first
message.attach(part1)
message.attach(part2)
# convert message to string
text = message.as_string()
with smtplib.SMTP_SSL(host='__MYHOST__', port=587) as server:
server.login(credentials.user, credentials.paswd)
server.sendmail(sender_email, message["To"].split(",") + message["Cc"].split(","), text)
它不是直接的 Python 問題,而是 MIME 問題。
您的消息包含正文和附件,正文是替代消息(可查看為 HTML 或文本)。 所以你的消息結構應該是:
MIXED
| ALTERNATIVE
| | text part
| | html part
| attachment
因此,與其將part1
和part2
附加到主消息,不如首先構建一個MIMEMultipart
替代方案來包含它們並將其附加到主消息:
...
body = MIMEMultipart("alternative")
body.attach(part1)
body.attach(part2)
message.attach(body)
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.