Sending HTML email

Posted: April 12th, 2010 | Author: Davo | Filed under: Django | Tags: , | 7 Comments »

It is possible to send a HTML email using the EmailMultiAlternatives

Example:

from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags

subject, from_email, to = 'Order Confirmation', 'admin@yourdomain.com', 'someone@somewhere.com'

html_content = render_to_string('the_template.html', {'varname':'value'}) # ...
text_content = strip_tags(html_content) # this strips the html, so people will have the text as well.

# create the email, and attach the HTML version as well.
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

7 Comments on “Sending HTML email”

  1. 1 Leandro said at 5:14 pm on July 7th, 2010:

    Great, very useful!

  2. 2 May SK. said at 9:28 am on July 28th, 2010:

    is “text_content” forced to be fill in? I’ve tried taken it out and it didn’t work. however, this is very good stuff.

  3. 3 Davo said at 4:02 pm on July 28th, 2010:

    It is suggested to send BOTH formats in case of some of the Email Clients cant display HTML. The “text_content” as you can see will be HTML stripped in this case.

  4. 4 ark said at 2:50 pm on September 28th, 2010:

    thanks, it’s perfect !

  5. 5 sam said at 2:46 pm on October 20th, 2010:

    Thanks but I am facing a small problem.
    The emails received have the Content headers (Content charset…..)
    as part of the message:

    I am using this is as a tamplate :

    Dear Valued Customer,

    We have identified that your below DID’s are not registered with 911 Addresses:

    {% for did in alldids %}
    {{ did }}
    {% endfor %}

    Please use this link to access our account registration page: http://{{ site }}/register/{{ key }}/

    Thank you

  6. 6 Muhammed K K said at 6:13 pm on January 2nd, 2011:

    Thanks dude I was searching for it. I am gonna try it.

  7. 7 crossan said at 12:22 pm on March 25th, 2011:

    Nice – worked a treat. Cheers feller!


Leave a Reply