【发布时间】:2015-03-05 08:43:10
【问题描述】:
首先:我读过这些:
- Issue with smtplib sending mail with unicode characters in Python 3.1
- Python - How to send utf-8 e-mail?
- Python 3 smtplib send with unicode characters
现在读完这些我知道如何创建和发送 utf8 邮件了。但我想转发邮件。我的(简化的)代码如下所示:
msg = email.parser.Parser().parse(sys.stdin)
# I also tried reading from a file, makes no difference
# left out some code adding ascii-only headers to the mail
with smtplib.SMTP(conf.smtp_server, conf.smtp_port) as s:
s.starttls()
s.ehlo()
s.login(conf.smtp_user, conf.smtp_password)
s.send_message(msg, conf.smtp_srcadr, destinations)
我得到的是这样的:
File "./mailer.py", line 38, in send_mail
s.send_message(msg, conf.smtp_srcadr, destinations)
File "/package/host/localhost/python-3.3/lib/python3.3/smtplib.py", line 822, in send_message
g.flatten(msg_copy, linesep='\r\n')
File "/package/host/localhost/python-3.3/lib/python3.3/email/generator.py", line 112, in flatten
self._write(msg)
File "/package/host/localhost/python-3.3/lib/python3.3/email/generator.py", line 164, in _write
self._dispatch(msg)
File "/package/host/localhost/python-3.3/lib/python3.3/email/generator.py", line 190, in _dispatch
meth(msg)
File "/package/host/localhost/python-3.3/lib/python3.3/email/generator.py", line 407, in _handle_text
super(BytesGenerator,self)._handle_text(msg)
File "/package/host/localhost/python-3.3/lib/python3.3/email/generator.py", line 220, in _handle_text
self.write(payload)
File "/package/host/localhost/python-3.3/lib/python3.3/email/generator.py", line 381, in write
self._fp.write(s.encode('ascii', 'surrogateescape'))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 505-506: ordinal not in range(128)
我的问题是:我不知道输入邮件的结构。我不能只是正确地编码它。我必须为各种多部分的可能性做好准备。有什么想法吗?
注意:
msg.as_string()
工作正常,并按预期包含 unicode 字符。
【问题讨论】:
-
相关:How can I send email using Python? 提供了代码示例,展示了如何在 Python 2 和 3 上使用非 ascii 字符发送电子邮件。这是另一个 Unicode-email code example
标签: python email python-3.x unicode smtp