Django – generate a plain text version of an html email
Asked Answered
H

2

10

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, '[email protected]', ['[email protected]'])
msg.attach_alternative(html_content, "text/html")
msg.send()

How can I do this without duplicating email templates?

Hansen answered 3/8, 2017 at 2:44 Comment(0)
H
19

Here is a solution:

import re
from django.utils.html import strip_tags

def textify(html):
    # Remove html tags and continuous whitespaces 
    text_only = re.sub('[ \t]+', ' ', strip_tags(html))
    # Strip single spaces in the beginning of each line
    return text_only.replace('\n ', '\n').strip()

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

The idea is to use strip_tags to remove html tags and to strip all extra whitespaces while preserving newlines.

This is how the result will look like:

<div style="width:600px; padding:20px;">
    <p>Hello,</p>
    <br>
    <p>Lorem ipsum</p>
    <p>Hello world</p> <br>
    <p> 
        Best regards, <br>
        John Appleseed
    </p>
</div>

--->

Hello,

Lorem ipsum
Hello world

Best regards,
John Appleseed
Hansen answered 3/8, 2017 at 2:44 Comment(0)
B
3

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)
Bukharin answered 16/1, 2020 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.