[Django]-Sending HTML email in django

10👍

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.

👤Bartek

19👍

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

12👍

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

Leave a comment