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

如何用Jinja2与Python渲染HTML邮件模板?

问题解决:Jinja2独立渲染HTML邮件模板

核心原因

浏览器不支持Jinja2语法,你手里的dynamic.html是模板文件,包含Jinja的循环、变量标签,浏览器只会把这些标签当成普通文本显示。只有通过Python脚本用Jinja2引擎渲染后,才能生成纯HTML内容,浏览器才能正确解析。

你不需要Flask

完全正确,Jinja2可以脱离Flask独立使用,你的现有脚本已经实现了核心渲染逻辑,不需要额外引入Flask。

解决方案

1. 把渲染后的HTML保存为可直接打开的文件

修改你的Python脚本,在渲染后添加保存文件的代码,就能得到一个纯HTML文件,浏览器打开它就能看到正确渲染的内容:

from jinja2 import Environment, FileSystemLoader

env = Environment(
    loader=FileSystemLoader('.')
)

template = env.get_template('dynamic.html')

def get_data():
    return {
         "movies": [
             {         
                 "title": 'Terminator',
                 "description": 'One soldier is sent back to protect her from the killing machine. He must find Sarah before the Terminator can carry out its mission.'
             },
             {                 
                 "title": 'Seven Years in Tibet',
                 "description": 'Seven Years in Tibet is a 1997 American biographical war drama film based on the 1952 book of the same name written by Austrian mountaineer Heinrich Harrer on his experiences in Tibet.'
             },
             {                
                 "title": 'The Lion King',
                 "description": 'A young lion prince is born in Africa, thus making his uncle Scar the second in line to the throne. Scar plots with the hyenas to kill King Mufasa and Prince Simba, thus making himself King. The King is killed and Simba is led to believe by Scar that it was his fault, and so flees the kingdom in shame.'
             }
         ]
    }

data = get_data()

# 渲染模板
output = template.render(data=data)

# 保存渲染后的HTML到文件
with open('rendered_email.html', 'w', encoding='utf-8') as f:
    f.write(output)

print("渲染完成,已生成rendered_email.html")

运行python script.py后,目录下会生成rendered_email.html,直接用浏览器打开这个文件就能看到正确的渲染结果。

2. 直接用于邮件发送

如果是要发送邮件,不需要保存文件,直接把output字符串作为邮件的HTML内容即可。比如用Python内置库发送:

# 接上面的代码,渲染得到output之后
import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 配置邮件信息
sender = 'your_email@example.com'
receivers = ['recipient@example.com']

# 创建HTML邮件对象
message = MIMEText(output, 'html', 'utf-8')
message['From'] = Header("邮件发送者", 'utf-8')
message['To'] = Header("邮件接收者", 'utf-8')
message['Subject'] = Header("电影荣誉提及", 'utf-8')

# 发送邮件(以QQ邮箱为例,其他邮箱需调整SMTP地址和端口)
try:
    smtp_obj = smtplib.SMTP_SSL('smtp.qq.com', 465)
    smtp_obj.login(sender, 'your_email_auth_code')  # 使用邮箱授权码而非登录密码
    smtp_obj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")
except smtplib.SMTPException as e:
    print(f"邮件发送失败: {e}")

额外优化建议

  • 你的get_data函数原本返回列表包裹的字典,直接返回字典更简洁,上面的代码已做调整。
  • 邮件模板尽量用表格布局(你已这么做),避免复杂CSS,不同邮箱客户端对CSS的支持差异较大。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 21:45:01