You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python发送HTML表格至Outlook失败:收到空邮件求助

解决Python发送Outlook HTML邮件内容为空的问题

问题根源分析

  1. MIME对象属性误用
    原代码中msg.HTMLBody=html是错误写法,MIMEMultipart对象不存在该属性——这是Outlook COM接口的用法,并非smtplib搭配MIME库的标准操作方式,直接赋值会导致HTML内容无法被邮件协议识别。

  2. HTML代码语法残缺
    原HTML片段缺少开头的<符号,且存在未闭合的<tr>、<tbody>、<table>标签,还有多余的>符号,邮件客户端无法解析这种不完整的HTML,最终导致内容为空。

修正后的代码

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# 配置Outlook SMTP参数
SERVER = 'smtp.office365.com'
PORT = 587
email_list = ['收件人邮箱@example.com']
sender_email = '你的Outlook邮箱@outlook.com'
sender_password = '你的邮箱密码/应用密码'  # 开启两步验证需用应用密码

# 构建邮件容器
msg = MIMEMultipart('alternative')
msg['Subject'] = "HTML表格测试邮件"
msg['From'] = sender_email
msg['To'] = ', '.join(email_list)

# 修复后的完整HTML表格代码
html = """
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th>DG Lead</th>
      <th>数值</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Krishnamurthy Ramamurthy</td>
      <td>324</td>
    </tr>
  </tbody>
</table>
"""

# 封装HTML内容并附加到邮件
html_content = MIMEText(html, 'html', 'utf-8')
msg.attach(html_content)

# 连接服务器发送邮件
with smtplib.SMTP(SERVER, PORT) as s:
    s.starttls()  # Outlook要求启用TLS加密
    s.login(sender_email, sender_password)
    s.send_message(msg)

关键注意事项

  • 必须通过MIMEText封装HTML内容,再附加到MIMEMultipart对象,这是smtplib发送HTML邮件的标准流程。
  • Outlook SMTP服务器强制要求TLS加密(端口587),且必须完成身份验证;若账号开启两步验证,需使用微软账号的应用密码替代原密码。
  • HTML代码需保证标签完整闭合,否则邮件客户端会因解析失败隐藏内容。

内容的提问来源于stack exchange,提问作者newjenkinsuser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 01:57:37