1

我有这个小的 Python 3 代码:

# -*- coding: utf-8 -*-

import smtplib
from email.mime.text import MIMEText

emailTextHTML = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-type" content="text/html;charset=UTF-8"><title>Wöchentliche Ticketbenachrichtigung</title></head><body><p>Hallo ...,</p></body></html>'
msg = MIMEText(emailTextHTML, 'html')
msg['Subject'] = 'TEST Wöchentliche Ticketbenachrichtigung TEST'
msg['From'] = 'reminderscript@blubb.de'
msg['To'] = 'asdf@blubb.de'
s = smtplib.SMTP('192.168.115.99')
#try:
s.send_message(msg)
#except:
print(msg)
s.quit()

现在的问题是它在 Windows 7 x64 上使用 Python 3.3.2 运行良好,但在 Debian Linux x64 上使用 Python 3.2.3 却失败了。使用上次设置时出现此错误:

Traceback (most recent call last):
  File "testing.py", line 13, in <module>
    s.send_message(msg)
  File "/usr/lib/python3.2/smtplib.py", line 812, in send_message
    g.flatten(msg_copy, linesep='\r\n')
  File "/usr/lib/python3.2/email/generator.py", line 91, in flatten
    self._write(msg)
  File "/usr/lib/python3.2/email/generator.py", line 137, in _write
    self._dispatch(msg)
  File "/usr/lib/python3.2/email/generator.py", line 163, in _dispatch
    meth(msg)
  File "/usr/lib/python3.2/email/generator.py", line 398, in _handle_text
    super(BytesGenerator,self)._handle_text(msg)
  File "/usr/lib/python3.2/email/generator.py", line 201, in _handle_text
    self.write(payload)
  File "/usr/lib/python3.2/email/generator.py", line 357, in write
    self._fp.write(s.encode('ascii', 'surrogateescape'))
UnicodeEncodeError: 'ascii' codec can't encode character '\xf6' in position 188: ordinal not in range(128)

字符串中的德语变音符号导致了这种情况。但是为什么它在 Windows 上成功而在 Linux 上失败了呢?我该怎么做才能使代码与这两种环境兼容?我想,控制台编码在这里似乎无关紧要。

4

2 回答 2

2

解决方案是将第 7 行从

msg = MIMEText(emailTextHTML, 'html')

msg = MIMEText(emailTextHTML, 'html', 'utf-8')

现在它适用于两种环境。

Python 错误730414380似乎与此有关。所以我的问题更多是 Python 3.2 到 3.3 的问题。

于 2013-09-02T12:41:19.800 回答
0

是的,正如您在https://stackoverflow.com/a/18573582/1346705中所写。Python 3.3 包含在MIMEText.__init__()

    # If no _charset was specified, check to see if there are non-ascii
    # characters present. If not, use 'us-ascii', otherwise use utf-8.
    # XXX: This can be removed once #7304 is fixed.
    if _charset is None:
        try:
            _text.encode('us-ascii')
            _charset = 'us-ascii'
        except UnicodeEncodeError:
            _charset = 'utf-8'

Python 3.2 不包含该特定代码。

应该指定字符集(显式或固定,如 3.3 或以某种方式)的原因是有时open等函数使用操作系统首选编码。这可能会使事情复杂化。此外,print在您的情况下,可能会导致类似的问题,因为控制台通常不使用 Unicode。

于 2013-09-02T13:08:07.417 回答