【问题标题】:SMTP encode error Python 3 after parsing the mail解析邮件后 SMTP 编码错误 Python 3
【发布时间】:2015-03-05 08:43:10
【问题描述】:

首先:我读过这些:

现在读完这些我知道如何创建和发送 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 字符。

【问题讨论】:

标签: python email python-3.x unicode smtp


【解决方案1】:

好的。我找到了一个 hacky 解决方案: 而不是基于 email.Message 的send_message 我使用基于字节的sendmail

s.sendmail(conf.smtp_srcadr, destinations, msg.as_string().encode('utf-8'))

我真的更喜欢基于 (Bytes-)Generator 或 Python 标准库中的其他电子邮件工具的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 2013-07-25
    • 2015-01-29
    • 2014-07-17
    • 1970-01-01
    • 2015-03-29
    相关资源
    最近更新 更多