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

Python向HTML邮件正文插入变量且不破坏Content-ID的方法

问题根因

两种报错本质都是字符串格式化逻辑不完整/冲突导致的:

  • 初版代码调用.format()时只传入了image_cid参数,模板里的{provinces_on_fire_str}占位符没有对应传入值,直接触发变量不存在报错。
  • 混合f-string和.format()的写法存在逻辑错误:f-string在字符串定义时就会把{image_cid}替换为make_msgid()生成的带尖括号的完整cid(格式为<随机串@域名>),后续调用.format()时字符串里已经没有{image_cid}占位符,传入的去尖括号cid参数不会生效,最终img标签里的cid带多余尖括号,和附件绑定的cid不匹配,图片自然无法加载。
修复方案

不要混用字符串格式化语法,选任意一种统一传入所有占位符参数即可。

方案1:统一使用.format()传参

把两个占位符对应的参数都传入.format()方法,确保image_cid传入的是去掉首尾尖括号的值:

# 设置纯文本正文
msg.set_content('This is a plain text body.')

# 生成图片的Content-ID
image_cid = make_msgid()

# 添加HTML格式正文
msg.add_alternative("""\
<html>
    <body>
        <p>This e-mail contains information about fires reported in the past 3 days.<br>
        The VIIRS sensor has reported wildfires in the following provinces: {provinces_on_fire_str} 
        
        This e-mail was sent automatically. 
        </p>
        <img src="cid:{image_cid}">
    </body>
</html>
""".format(
    provinces_on_fire_str=provinces_on_fire_str,
    image_cid=image_cid[1:-1]
), subtype="html")

# 挂载图片附件
with open(f"path/toimage/{today}.png", 'rb') as img:
    maintype, subtype = mimetypes.guess_type(img.name)[0].split("/")
    msg.get_payload()[1].add_related(img.read(),
                                     maintype=maintype,
                                     subtype=subtype,
                                     cid=image_cid)

方案2:纯f-string实现

如果偏好f-string语法,直接在f-string内完成image_cid的切片处理,不要后续追加.format()调用:

# 设置纯文本正文
msg.set_content('This is a plain text body.')

# 生成图片的Content-ID
image_cid = make_msgid()

# 添加HTML格式正文
msg.add_alternative(f"""\
<html>
    <body>
        <p>This e-mail contains information about fires reported in the past 3 days.<br>
        The VIIRS sensor has reported wildfires in the following provinces: {provinces_on_fire_str}
        
        This e-mail was sent automatically.
        </p>
        <img src="cid:{image_cid[1:-1]}">
    </body>
</html>
""", subtype="html")

# 挂载图片附件
with open(f"path/toimage/{today}.png", 'rb') as img:
    maintype, subtype = mimetypes.guess_type(img.name)[0].split("/")
    msg.get_payload()[1].add_related(img.read(),
                                     maintype=maintype,
                                     subtype=subtype,
                                     cid=image_cid)

注意:make_msgid()生成的cid自带首尾尖括号,绑定附件时直接用原始值即可,写在img标签src里的cid必须去掉这两个尖括号,否则会出现cid匹配失败、图片无法加载的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 07:51:28