Django – 生成 html 电子邮件的纯文本版本

Django – generate a plain text version of an html email

我想通过提供纯文本和 html 版本的电子邮件来提高送达率:

text_content = ???
html_content = ???

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

如何在不复制电子邮件模板的情况下执行此操作?

这是一个解决方案:

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)

想法是使用 strip_tags 删除 html 标签并去除所有多余的空格,同时保留换行符。

结果如下所示:

<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

将 html 转换为文本的另一种方法是使用 html2text (你必须安装它):

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)