3

我正在使用 Python 向 gmail 帐户发送电子邮件。这是我正在使用的代码

msg = email.mime.multipart.MIMEMultipart()
msg['From'] = 'myemail@gmail.com'
msg['To'] = 'toemail@gmail.com'
msg['Subject'] = 'HTML test'
msg_html = email.mime.text.MIMEText('<html><head></head><body><b>This is HTML</b></body></html>', 'html')
msg_txt = email.mime.text.MIMEText('This is text','plain')
msg.attach(msg_html)
msg.attach(msg_txt)
#SNIP SMTP connection code
smtpConn.sendmail('myemail@gmail.com', 'toemail@gmail.com', msg.as_string())

当我在 gmail 中查看这封电子邮件时,HTML 和文本版本都显示如下:

这是 HTML

这是文字

它应该是显示文本或 html,这是导致此行为的原因。

4

1 回答 1

9

The message is being sent as multipart/mixed (as this is the default) when it needs to be sent as multipart/alternative. mixed means that each part contains different content and all should be displayed, while alternative means that all parts have the same content in different formats and only one should be displayed.

msg = email.mime.multipart.MIMEMultipart("alternative")

Additionally, you should put the parts in increasing order of preference, i.e., text before HTML. The MUA (GMail in this case) will render the last part it knows how to display.

See the Wikipedia article on MIME for a good introduction to formatting MIME messages.

于 2014-08-28T17:13:46.720 回答