Skip to main content
 首页 » 编程设计

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

2024年08月20日41birdshome

我想通过提供电子邮件的纯文本和 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