在 Django 中发送 HTML 电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3237519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:46:05  来源:igfitidea点击:

Sending HTML email in django

htmldjangodjango-templateshtml-email

提问by crivateos

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'

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

in {{ n.date }}within text_email template

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

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

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

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

采纳答案by Bartek

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, rendertakes a Contextso you need to do this:

然后尝试将该字典用作 render() 方法的一部分。但是,render需要一个Context所以你需要这样做:

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

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

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

回答by crivateos

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

回答by Super Scary

They've updated send_mailto allow html messages in the dev version

他们已更新send_mail以允许开发版本中的 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('/')