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

Python实现邮件正文同时嵌入图片与DataFrame报错求助

解决邮件中同时嵌入图片和DataFrame时的KeyError问题

嘿,我看到你在尝试给邮件同时嵌入图片和DataFrame时遇到了KeyError: 'table'的问题,咱们来拆解一下问题根源,然后给出修复方案。

报错原因分析

你当前代码的核心问题是HTML模板格式化的顺序错误:

  • 你的HTML模板里有两个占位符:{table}和{image_cid}
  • 你在调用.format(image_cid=image_cid[1:-1])的时候,只传入了image_cid参数,完全没处理{table}占位符,Python找不到对应的键就抛出了KeyError
  • 而且你处理DataFrame生成表格HTML的代码放在了添加HTML邮件内容之后,这完全颠倒了顺序

修正后的完整代码

首先确保你已经安装了tabulate库(如果没装的话先跑pip install tabulate),然后用下面的代码替换你的原有代码:

from email.message import EmailMessage
from email.utils import make_msgid
import mimetypes
from tabulate import tabulate
import pandas as pd

# 假设你的df_2是已经定义好的DataFrame
# df_2 = pd.read_csv("your_data.csv")  # 示例:如果是从CSV读取的话

# 1. 先处理DataFrame,生成HTML格式的表格
col_list = list(df_2.columns.values)
table_html = tabulate(df_2, headers=col_list, tablefmt="html")

# 2. 创建邮件对象并设置基础信息
msg = EmailMessage()
msg['Subject'] = 'Hello there'
msg['From'] = 'abhishek.gupta1608@gmail.com'
msg['To'] = 'abhishek.gupta@pharmeasy.in'

# 3. 设置纯文本备用内容
msg.set_content('This is a plain text body.')

# 4. 生成图片的Content-ID
image_cid = make_msgid(domain='xyz.com')
# 移除CID两端的<>,方便在HTML里使用
clean_image_cid = image_cid[1:-1]

# 5. 添加HTML邮件内容,同时传入table和image_cid参数
msg.add_alternative("""\
<html>
<head>
<style>
 table, th, td {{ border: 1px solid black; border-collapse: collapse; }}
 th, td {{ padding: 5px; }}
</style>
</head>
<body>
<p>This is an HTML body.<br>
 {table}
</p>
<img src="cid:{image_cid}">
</body>
</html>
""".format(table=table_html, image_cid=clean_image_cid), subtype='html')

# 6. 嵌入图片到邮件中
with open('/Users/abhishekgupta/mybarchart.png', 'rb') as img:
    maintype, subtype = mimetypes.guess_type(img.name)[0].split('/')
    # 找到HTML部分的payload,添加关联的图片
    msg.get_payload()[1].add_related(img.read(), maintype=maintype, subtype=subtype, cid=image_cid)

# 后续可以用smtplib发送邮件,示例:
# import smtplib
# with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
#     smtp.login('your_email@gmail.com', 'your_app_password')
#     smtp.send_message(msg)

关键修改点说明

  • 调整顺序:先把DataFrame转换成HTML表格,再格式化HTML模板,确保模板里的{table}有对应的参数值
  • 一次性传参:调用.format()时同时传入table=table_html和image_cid=clean_image_cid,让两个占位符都被正确替换
  • 变量拆分:把清理后的CID单独存为clean_image_cid,代码更清晰
  • 明确依赖:添加了tabulate和pandas的导入(如果你的代码里已经有了可以忽略)

这样修改后,邮件就能同时显示格式化的表格和嵌入的图片啦,不会再出现KeyError的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:27:35