Python如何将DataFrame与图片同时嵌入邮件HTML正文
可行实现方案
错误原因说明
- 不能重复调用
add_alternative添加HTML内容:multipart/alternative结构用于存放不同类型的同一份内容(比如纯文本版、HTML版),重复添加HTML会导致结构异常触发contentmanager相关报错 - 无需将DataFrame表格单独添加为附件/关联资源,直接将
df.to_html()生成的表格代码插入到原有HTML模板即可,format支持同时传入多个占位符,不存在被图片逻辑占用的问题
完整修改代码
#!/usr/bin/env python3 import smtplib import pandas as pd import numpy as np from email.message import EmailMessage from email.headerregistry import Address from email.utils import make_msgid # 1. 构造测试用DataFrame df = pd.DataFrame( {'A': [419,382, 382, 382, 411, 411, 411], 'B': [2,2,3,3,3,3,6], 'C': np.random.randn(7)*10, 'D': list('abcdefg') } ) # 转HTML时可加样式参数,比如显示边框、隐藏索引 df_html = df.to_html(border=1, index=False) # 2. 构造邮件基础信息 msg = EmailMessage() msg['Subject'] = "Ayons asperges pour le déjeuner" msg['From'] = Address("Pepé Le Pew", "pepe", "example.com") msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"), Address("Fabrette Pussycat", "fabrette", "example.com")) msg.set_content("""\ Salut! Cela ressemble à un excellent recipie[1] déjeuner. [1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718 --Pepé """) # 3. 构造HTML模板,新增表格占位符{df_table} asparagus_cid = make_msgid() msg.add_alternative("""\ <html> <head></head> <body> <p>Salut!</p> <p>Cela ressemble à un excellent <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718"> recipie </a> déjeuner. </p> <h3>数据表格</h3> {df_table} <br> <img src="cid:{asparagus_cid}" /> </body> </html> """.format( asparagus_cid=asparagus_cid[1:-1], df_table=df_html ), subtype='html') # 4. 添加关联图片 with open("roasted-asparagus.jpg", 'rb') as img: msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg', cid=asparagus_cid) # 5. 本地存储/发送邮件 with open('outgoing.msg', 'wb') as f: f.write(bytes(msg)) with smtplib.SMTP('localhost') as s: s.send_message(msg)
注意事项
如果需要调整表格样式,可以直接对df.to_html()生成的字符串做替换,比如给表格加内联CSS样式,适配不同邮件客户端的显示规则。
内容的提问来源于stack exchange,提问作者gregV
相关产品推荐
相关产品推荐

