Python/Django : Email template is not rendered. 显示 html 标签并且不转换实体

标签 python django email django-templates

我正在使用模板发送电子邮件,但该模板未正确呈现。它显示 html 标签并且不呈现特殊字符。

它确实渲染上下文,例如,如果我为其提供“username”:some_name,那么当我执行 {{username}} 时,它将正确显示用户名

my_template.html:

<p>hello &oslash;</p>

在 View 中:

from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context

t = get_template('my_template.html')
msg = EmailMultiAlternatives("hi", t.render(Context({})), from_email, [user.email])
msg.send()

显示收到的电子邮件,并显示 p 标签。此外,该实体的显示与模板中所写的完全一样。我只需使用 .txt 文件就可以了,除非我需要渲染特殊字符。如果我直接将它们写入 txt 文件,则在尝试发送时会收到错误。

我也尝试过使用django的send_mail()。还可以在模板中添加 html 标签。相同的结果。

最佳答案

多部分/替代电子邮件有两个部分:

  1. 电子邮件的纯文本版本
  2. 电子邮件的 html 版本

所以这里你只需要执行#2 并添加 html 部分!

按照此处的示例... https://docs.djangoproject.com/en/dev/topics/email/#sending-alternative-content-types ...您可能只需要在 msg.send() 之前添加这样的行`

msg.attach_alternative(t.render(Context({})), "text/html")

关于Python/Django : Email template is not rendered. 显示 html 标签并且不转换实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13285976/

相关文章:

Python 帮助 |从底部读取文本文件中的数据

python - SQL 插入不起作用(没有出现错误)

python - 删除 django 模板中的 [u'']

javascript - 是否可以仅通过客户端发送电子邮件?

email - 如何通过 Gmail 推送通知获取新邮件详细信息?

python - 将 Pandas DataFrame 写入 Google Cloud Storage 或 BigQuery

ajax - django ajax 代理 View

python - 使用 django 将数据加载到外部文本文件中

ios - 如何使用 Mailgun 在 Swift 中发送电子邮件

python - Unicode Python Windows 控制台