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

能否在HTML格式邮件中传递参数?基于Python操作Outlook的实现疑问

解决Outlook邮件中Python变量未显示的问题

嘿,我懂你的困扰啦——你想把Python里的text变量内容插入到Outlook邮件的HTML正文里,但现在邮件显示的是{text}占位符而不是实际的字符串值,对吧?这不是功能不可行,只是你漏掉了关键的变量替换步骤而已😎

问题根源

你定义的html_body是一个字符串模板,里面的{text}只是一个普通的文本占位符,Python并不会自动识别并替换它为变量值。你需要主动告诉Python把变量text的内容填充到这个位置。

修正方案

这里有几种简单的方法来完成变量替换,都是Python里常用的字符串处理技巧:

方法1:使用f-string(推荐,Python 3.6+支持)

在字符串模板前加上f前缀,这样Python会自动把{text}替换成对应的变量值:

text = "wloasdlfkjasldkfjasf"
html_body = f"""
<div>
<h1 style="font-family: 'Lucida Handwriting'; font-size: 56; font-weight: bold; color: #9eac9c;"> Happy Birthday!! </h1>
<span style="font-family: 'Lucida Sans'; font-size: 28; color: #8d395c;"> {text} </span>
</div><br>
<div>
<img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/cute-birthday-instagram-captions-1584723902.jpg" width=50%>
</div>
"""
message.HTMLBody = html_body

方法2:使用str.format()方法(兼容旧版Python)

如果你的Python版本低于3.6,可以用format()方法来手动传递变量:

text = "wloasdlfkjasldkfjasf"
html_body = """
<div>
<h1 style="font-family: 'Lucida Handwriting'; font-size: 56; font-weight: bold; color: #9eac9c;"> Happy Birthday!! </h1>
<span style="font-family: 'Lucida Sans'; font-size: 28; color: #8d395c;"> {text} </span>
</div><br>
<div>
<img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/cute-birthday-instagram-captions-1584723902.jpg" width=50%>
</div>
""".format(text=text)
message.HTMLBody = html_body

额外提示:处理特殊字符

如果你的text变量里包含HTML特殊字符(比如<、>、&),直接插入可能会破坏HTML结构,建议用html.escape()转义:

import html
text = "Hey, check this: <example.com>"
html_body = f"""
...
<span style="font-family: 'Lucida Sans'; font-size: 28; color: #8d395c;"> {html.escape(text)} </span>
...
"""

补充说明

你代码里先设置message.HTMLBody = "<b> wishing you </b>"再赋值message.HTMLBody = html_body是没问题的,后者会覆盖前者的内容,符合你的需求。

按照上面的方法修改后,邮件里就能正常显示text变量的字符串值啦!

内容的提问来源于stack exchange,提问作者Bar Ben-ezra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 13:02:40