我发了一封带有python脚本的邮件。它是由纯文本、html和附件组成的多部分邮件。
邮件是正确发送的,但是在某些客户端,附件没有出现。我在this discussion中读到,用"html“或”混合“来改变"alternative”可以解决问题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) 发布于 2022-03-08 08:53:00
这不是一个直接的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)
...https://stackoverflow.com/questions/71392065
复制相似问题