gpt4 book ai didi

html - 在 Django 中发送 HTML 电子邮件

转载 作者:技术小花猫 更新时间:2023-10-29 12:01:02 25 4
gpt4 key购买 nike

在我的项目中,我添加了一个时事通讯提要。但是当尝试使用此功能发送电子邮件时:

def send(request):
template_html = 'static/newsletter.html'
template_text = 'static/newsletter.txt'
newsletters = Newsletter.objects.filter(sent=False)
subject = _(u"Newsletter")
adr = NewsletterEmails.objects.all()
for a in adr:
for n in newsletters:
to = a.email
from_email = settings.DEFAULT_FROM_EMAIL
subject = _(u"Newsletter Fandrive")
text = get_template(template_text)
html = get_template(template_html)
d = { 'n': n,'email': to }
text_content = text.render(d)
html_content = html.render(d)

msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

使用这些模板:

//text

=================== Newsletter - {{ n.date }} ============
==========================================================
{{ n.title }}
==========================================================
{{ n.text }}
==========================================================

//html

<html>
<head>
</head>
<body>
<div style="">
<div style="">
<h1 style="">{{ n.title }} - {{n.date}}</h1>
<p style="">
{{ n.text }}
</p>
</div>
</div>
</body>
</html>

和模型:

class Newsletter(models.Model):
title = models.CharField("title", blank=False, max_length=50)
text = models.TextField("text", blank=False)
sent = models.BooleanField("sent", default=False)
data = models.DateTimeField("creation date", auto_now_add=True, blank=False)

class NewsletterEmails(models.Model):
email = models.EmailField(_(u"e-mail address"),)

我得到:

TemplateSyntaxError at /utils/newsletter_send/<br/>
Caught an exception while rendering: 'dict' object has no attribute 'autoescape'

{{ n.date }} 在 text_email 模板中

尽管我的调试显示我正在向模板发送正确的时事通讯对象以及调试上下文:

context {'email': u'admin@domain.com', 'n': <Newsletter: Newsletter object>}

为什么会这样?从我发现的这个错误来看,它以某种方式连接到将空字典发送到模板渲染器,但我的不是空的...

最佳答案

仅供引用。我找到了另一种方法:

def send(request):
template_html = 'static/newsletter.html'
template_text = 'static/newsletter.txt'
newsletters = Newsletter.objects.filter(sent=False)
subject = _(u"Newsletter Fandrive")
adr = NewsletterEmails.objects.all()
for a in adr:
for n in newsletters:
to = a.email
from_email = settings.DEFAULT_FROM_EMAIL
subject = _(u"Newsletter Fandrive")

text_content = render_to_string(template_text, {"title": n.title,"text": n.text, 'date': n.date, 'email': to})
html_content = render_to_string(template_html, {"title": n.title,"text": n.text, 'date': n.date, 'email': to})

msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

return HttpResponseRedirect('/')

关于html - 在 Django 中发送 HTML 电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3237519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com