2013-07-26 34 views
1

我一直在用EmailMessage類產生一個神祕的bug,在這裏我發送的最後一封電子郵件以「!」結尾。目前,我發送電子郵件與下面的代碼:Django EmailMessage send()在整個電子郵件中插入驚歎號(!)

html_content = render_to_string('layouts/option1.html', request.POST) 
    subject = "just a test email" 
    from_email = request.user.email 
    recipient = [from_email, ] 
    msg = EmailMessage(subject, html_content, from_email, to=recipient, headers={ 
     'Content-Type': 'text/html; charset=ISO-8859-1', 
     'MIME-Version': '1.0' 
    }) 
    msg.content_subtype = "html" 
    try: 
     msg.send() 
     response['success'] = True 
     response['html_content'] = html_content 
    except: 
     pass 

我發現了類似thread(但PHP),討論一些非常相似。顯然這與消息長度有關。實際上,我發送了一個相當長的html電子郵件,但我無法實現模擬他們在我的鏈接中提出的解決方案的pythonic版本。

有關如何防止「!」出現的任何幫助或建議將非常感謝!

謝謝 Fy的

回答

0

那麼這裏應該是PHP的解決方案的Python版本:

import textwrap 

html_content = render_to_string('layouts/option1.html', request.POST) 
encoded_content = '\r\n'.join(textwrap.wrap(html_content.encode('base64'), 76)) 
subject = "just a test email" 
from_email = request.user.email 
recipient = [from_email, ] 
msg = EmailMessage(subject, encoded_content, from_email, to=recipient, headers={ 
    'Content-Type': 'text/html; charset=ISO-8859-1', # why not UTF-8 here? 
    'Content-Transfer-Encoding': 'base64', 
    'MIME-Version': '1.0' 
}) 
msg.content_subtype = "html" 
try: 
    msg.send() 
    response['success'] = True 
    response['html_content'] = html_content 
except: 
    pass 

我沒有時間來測試這整個的功能,但希望這有助於!

+0

感謝您關於utf-8編碼的提示。這就是我最終解決的問題! – Fydo