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

如何在邮件正文字符串中将列表渲染为单列表格?

解决列表转嵌入邮件的HTML表格问题

核心思路

要在邮件正文中显示表格,需将列表动态生成HTML格式的表格代码,并确保邮件以HTML格式发送(而非纯文本),才能让邮件客户端正确渲染表格。

具体实现代码

names = ["John Appleseed", "Amy Adams", "Robert Feller"]

# 动态生成表格HTML代码
table_html = """
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Names</th>
</tr>
</thead>
<tbody>
"""
# 遍历列表自动生成每一行
for name in names:
    table_html += f"<tr><td>{name}</td></tr>\n"

table_html += """
</tbody>
</table>
</div>
"""

# 构造完整的HTML邮件正文
subject = 'Test'
body = f"""
<p>hello, here is your email</p>
{table_html}
"""

email_to = ['jackdaniels@gmail.com']

# 发送邮件时务必指定内容类型为HTML(根据你的email库调整参数)
email(email_to, subject, body, email.config, attachment, content_type='html')

关键注意事项

  • 动态行生成:通过for循环遍历列表,自动生成每一行的HTML代码,彻底避免手动编写每个条目。
  • HTML格式发送:必须确保邮件发送时设置内容类型为html,否则邮件客户端会把表格代码当作纯文本显示。如果你的email函数没有直接参数,可改用底层库(如smtplib+email.mime)创建MIMEText对象时指定_subtype='html'。
  • 样式兼容性:部分邮件客户端会过滤自定义CSS类(如示例中的s-table),若需要稳定样式,建议改用内联样式,比如:
    <table style="border-collapse: collapse; width: auto; border: 1px solid #ddd;">
    <th style="padding: 8px; text-align: left; border-bottom: 1px solid #ddd;">Names</th>
    <td style="padding: 8px; border-bottom: 1px solid #ddd;">John Appleseed</td>
    
  • DataFrame来源适配:如果列表是从DataFrame字段衍生的,直接用names = df['你的字段名'].tolist()替换即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:20:22