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

Max*_*ysh 5 python django django-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()
Run Code Online (Sandbox Code Playgroud)

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

Max*_*ysh 11

这是一个解决方案:

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)
Run Code Online (Sandbox Code Playgroud)

这个想法是用来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>
Run Code Online (Sandbox Code Playgroud)

--->

Hello,

Lorem ipsum
Hello world

Best regards,
John Appleseed
Run Code Online (Sandbox Code Playgroud)