Python发送HTML邮件:Outlook显示指定文本Gmail正常的问题求助
问题解决:Python发送HTML邮件在Outlook仅显示纯文本
核心问题分析
你遇到的情况是两个关键错误导致Outlook无法正确解析HTML内容:
1. set_content方法使用错误
set_content是用来设置邮件的纯文本备用内容,但你给它加了subtype="html"参数,这会混淆邮件客户端的内容识别逻辑。Outlook会优先读取这部分被错误标记的内容,忽略后续添加的HTML替代内容。
2. HTML正文存在语法不完整问题
代码拼接HTML时存在多处未闭合的标签和不完整属性:
<a href=\"{url}\" style='color:缺少颜色值、属性闭合及标签收尾Keywords对应的<span>标签未闭合<li>和<strong>标签也未正确闭合
这些语法错误会让Outlook解析HTML失败,最终 fallback到纯文本内容。
修正后的代码示例
# 修正HTML正文拼接,补全所有标签和属性 body = "<html><body><div style='background-color: #0072c6; padding: 10px;'>" body += "<h2 style='color: #fff; margin: 0;'>Latest News:</h2>" body += "</div><ul style='list-style-type: none; padding: 0;'>" for url_info in matching_urls: summary, title, date, name, keywords, url = url_info # 补全a标签样式、内容及标签闭合,完善li结构 body += f"<li style='margin-bottom: 10px;'><strong><a href=\"{url}\" style='color: #0072c6; text-decoration: none;'>{title}</a></strong><br>" body += f"<span style='font-size: 14px;'><strong>Date:</strong> {date}</span><br>" body += f"<span style='font-size: 14px;'><strong>Summary:</strong> {summary}</span><br>" body += f"<span style='font-size: 14px;'><strong>Keywords:</strong> {keywords}</span></li>" # 补全span和li标签闭合 body += "</ul></body></html>" em = EmailMessage() em["From"] = sender_email em["To"] = ", ".join(reciever_emails) em["Subject"] = subject # 正确设置纯文本备用内容,无需加subtype="html" em.set_content("请使用支持HTML的邮件客户端查看此邮件。") # 添加HTML替代内容 em.add_alternative(body, subtype="html") file_path = "/tmp/News.xlsx" with open(file_path, "rb") as excel_file: em.add_attachment( excel_file.read(), maintype="application", subtype="vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename="News.xlsx" ) context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as smtp: smtp.login(sender_email, password) smtp.sendmail(sender_email, reciever_emails, em.as_string())
额外提示
- 编写HTML邮件时,坚持使用内联样式(你已经这么做了,这很重要,因为Outlook对外部样式支持极差)
- 写完HTML后可以用在线校验工具检查语法,避免标签未闭合这类低级错误
内容的提问来源于stack exchange,提问作者bartu celasun
相关产品推荐
相关产品推荐

