Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending HTML email in django

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

like image 990
crivateos Avatar asked Jul 13 '10 13:07

crivateos


People also ask

How do I send a message in Django?

To add a message, call: from django. contrib import messages messages. add_message(request, messages.INFO, 'Hello world.

How do I send and receive emails in Django?

Use the get_new_mail method to collect new messages from the server. Go to Django Admin, then to 'Mailboxes' page, check all the mailboxes you need to receive emails from. At the top of the list with mailboxes, choose the action selector 'Get new mail' and click 'Go'.


3 Answers

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('/')
like image 119
crivateos Avatar answered Oct 14 '22 04:10

crivateos


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('/')
like image 29
Super Scary Avatar answered Oct 14 '22 04:10

Super Scary


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.

like image 10
Bartek Avatar answered Oct 14 '22 04:10

Bartek