我有这个小的 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 上失败了呢?我该怎么做才能使代码与这两种环境兼容?我想,控制台编码在这里似乎无关紧要。