在 django 中发送 HTML 电子邮件

发布于 2024-09-08 22:30:19 字数 2536 浏览 5 评论 0原文

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

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/
渲染时捕获异常:'dict'对象

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

没有属性'autoescape'虽然我的调试显示我正在将正确的新闻通讯对象发送到模板以及调试上下文:

context {'email': u'[ email protected]', 'n':}

为什么会发生这种情况?根据我发现的有关此错误的信息,它以某种方式与将空字典发送到模板渲染器有关,但我的字典不是空的......

In my project I've added a newsletter feed. But when trying to send emails with this function :

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

using those templates :

//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>

and models :

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

I'm getting :

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

in {{ n.date }} within text_email template

Although my debug shows I'm sending proper newsletter objects to the template ,as well as debug context :

context {'email': u'[email protected]', 'n': <Newsletter: Newsletter object>}

Why is that happening ? From what I've found about this error it is somehow connected to sending empty dictionary to template renderer, but mine's not empty...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

绾颜 2024-09-15 22:30:19

仅供参考。我找到了另一种方法:

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

Just for informational purpose. I've found another way of doing this :

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('/')
楠木可依 2024-09-15 22:30:19

他们更新了 send_mail 以允许在 dev 版本 中发送 html 消息

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

            send_mail(subject, text_content, from_email,
             to, fail_silently=False, html_message=html_content)
    return HttpResponseRedirect('/')

They've updated send_mail to allow html messages in the dev version

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

            send_mail(subject, text_content, from_email,
             to, fail_silently=False, html_message=html_content)
    return HttpResponseRedirect('/')
很快妥协 2024-09-15 22:30:19

这是一个非常简单的修复,你错过了一件小事。

您正在这样做:

  d = { 'n': n,'email': to }

然后尝试使用该字典作为 render() 方法的一部分。但是,render 需要一个 Context,因此您需要执行以下操作:

 d = Context({ 'n': n,'email': to })

确保也从 django.template 导入它。这应该可以解决您收到的错误。

This is a pretty simple fix, you're missing one minor thing.

You are doing this:

  d = { 'n': n,'email': to }

Followed by trying to use that dictionary as part of your render() method. However, render takes a Context so you need to do this:

 d = Context({ 'n': n,'email': to })

Make sure to import it from django.template as well. That should fix the error you are receiving.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文