Gmail会同时显示电子邮件的HTML和文本以及HTML部分

时间:2014-08-28 16:57:46

标签: python gmail mime-mail

我正在使用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,导致此行为的原因。

1 个答案:

答案 0 :(得分:7)

当消息需要以multipart/mixed的形式发送时,消息将以multipart/alternativethis is the default)的形式发送。 mixed表示每个部分都包含不同的内容,所有部分都应该显示,而alternative表示所有部分都以不同的格式具有相同的内容,只显示一个。

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

此外,您应该按照首选项的顺序放置部分,即HTML之前的文本。 MUA(在这种情况下为GMail)将呈现它知道如何显示的最后一部分。

有关格式化MIME邮件的详细介绍,请参阅Wikipedia article on MIME