Python- 已发送的 MIME 电子邮件附件未在某些客户端中显示

Python-sent MIME email attachments not showing up in some clients

我正在发送一封带有 python 脚本的电子邮件。 这是一封由纯文本 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

因此,与其将 part1part2 附加到主要消息,不如先构建一个 MIMEMultipart 替代方案来包含它们并将其附加到主要消息:

...
body = MIMEMultipart("alternative")
body.attach(part1)
body.attach(part2)
message.attach(body)
...