python template html_Python / Django:不渲染电子邮件模板。显示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:

hello ø

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:

a plain text version of the email

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值