1

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

它确实呈现了上下文,例如,如果我为它提供一个 "username":some_name 那么它会在我执行 {{username}} 时正确显示用户名

my_template.html:

<p>hello &oslash;</p>

在视图中:

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 标记。结果相同。

4

1 回答 1

1

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

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

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

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

msg.attach_alternative(t.render(Context({})), "text/html")
于 2012-11-08T09:32:49.987 回答