第一:我读过这些:
看完这些之后,我知道如何创建和发送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字符。
发布于 2015-01-07 15:54:13
好吧。我找到了一个麻烦的解决方案:而不是基于Email.Message的send_message,而是使用基于字节的sendmail。
s.sendmail(conf.smtp_srcadr, destinations, msg.as_string().encode('utf-8'))我非常喜欢基于(字节-)发生器或来自Python库的其他电子邮件工具的解决方案。
https://stackoverflow.com/questions/27819722
复制相似问题