1

我一直在与一个由 EmailMessage 类产生的神秘错误作斗争,其中我发送给自己的最后一封电子邮件以“!”插入整个正文。目前,我正在使用以下代码发送电子邮件:

   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

我发现了一个类似的线程(但对于 php),它讨论了一些非常相似的东西。显然这与消息长度有关。事实上,我正在发送一封相当长的 html 电子邮件,但我无法实现模仿他们在我的链接中提出的解决方案的 pythonic 版本。

任何有关如何防止“!”出现的帮助或建议将不胜感激!!!

谢谢你,飞

4

2 回答 2

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

我没有时间测试整个功能,但希望这会有所帮助!

于 2013-07-26T19:59:30.693 回答
0

这在 Django 1.10 中已在此 pull request中修复。

于 2016-11-04T06:25:17.153 回答