Python/Django: Email template is not rendered. Shows html tags and doesn't convert entities

China☆狼群 提交于 2019-12-11 05:05:21

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/13285976/python-django-email-template-is-not-rendered-shows-html-tags-and-doesnt-conve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!