2017-08-03 9 views
0
私はデリバリー率を向上させたい

のプレーンテキストバージョンを生成:はジャンゴ - 電子メールの両方のテキストのみとHTMLのバージョンを提供することにより、HTMLメール

text_content = ??? 
html_content = ??? 

msg = EmailMultiAlternatives(subject, text_content, '[email protected]', ['[email protected]']) 
msg.attach_alternative(html_content, "text/html") 
msg.send() 

どのように私は、電子メールテンプレートを複製せずにこれを行うことができますか?ここで

答えて

0

は、ソリューションです:

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) 

アイデアはhtmlタグを削除するstrip_tagsを使用し、改行を維持しながら、すべての余分な空白を除去することです。

<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 

これは、結果は次のようになります方法です

関連する問題