Django – generate a plain text version of an html email

Viewed 3570

I want to improve deliverability rates by providing both text-only and html versions of emails:

text_content = ???
html_content = ???

msg = EmailMultiAlternatives(subject, text_content, 'from@site.com', ['to@site.com'])
msg.attach_alternative(html_content, "text/html")
msg.send()

How can I do this without duplicating email templates?

2 Answers

Another way to covert html to text could be using html2text (you have to install it):

import html2text

def textify(html):
    h = html2text.HTML2Text()

    # Don't Ignore links, they are useful inside emails
    h.ignore_links = False
    return h.handle(html)


html = render_to_string('email/confirmation.html', {
    'foo': 'hello',
    'bar': 'world',
})
text = textify(html)
Related