python – Gmail同时显示电子邮件的HTML和文本以及HTML部分
发布时间:2020-12-20 11:37:23 所属栏目:Python 来源:网络整理
导读:我正在使用 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('htmlhe
我正在使用
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,导致此行为的原因. 解决方法
当需要作为multipart / alternative发送消息时,消息将作为multipart / mixed(如
this is the default)发送.混合意味着每个部分包含不同的内容,所有部分都应该显示,而替代意味着所有部分具有不同格式的相同内容,并且只应显示一个.
msg = email.mime.multipart.MIMEMultipart("alternative") 此外,您应该按优先级顺序放置部件,即HTML之前的文本. MUA(在这种情况下为GMail)将呈现它知道如何显示的最后一部分. 有关格式化MIME消息的详细介绍,请参阅Wikipedia article on MIME. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |