Python / Django:不渲染电子邮件模板。显示html标签,不转换实体 [英] Python/Django: Email template is not rendered. Shows html tags and doesn't convert entities

查看:214
本文介绍了Python / Django:不渲染电子邮件模板。显示html标签,不转换实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



它提供了上下文,例如,如果我提供一个用户名:some_name,那么当我{{username}}



my_template.html:

 < p> hello& oslash ;< / p为H. 

在视图中:

来自django.core.mail的导入EmailMultiAlternatives 
从django.template.loader导入get_template
从django.template导入上下文

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-内容类型 ...您可能只需要在msg.send()之前添加一行这样的代码。

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


I am sending emails using a template, but the template is not being properly rendered. It shows the html tags and doesn't render special chars.

It does render the context, for example if I supply it with a "username":some_name then it will properly display the username when I do {{username}}

my_template.html:

<p>hello &oslash;</p>

In views:

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()

The received email shows up with the p tags displayed. Also, the entity appears exactly as written in the template. I'd be fine just using a .txt file except that I need the special chars to be rendered. If I write them directly in the txt file, I get an error when trying to send it.

I have also tried using django's send_mail(). Also adding an html tag to the template. Same result.

解决方案

a multipart/alternative email has two parts:

  1. a plain text version of the email
  2. an html version of the email

so here you just gotta do #2 and add the html part!

following the example here... https://docs.djangoproject.com/en/dev/topics/email/#sending-alternative-content-types ...you'd probably just have to add a line like this before msg.send()`

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

这篇关于Python / Django:不渲染电子邮件模板。显示html标签,不转换实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆