Python3:发送包含二进制数据的电子邮件?
以下失败:
>>> a = email.message.Message()
>>> a.set_payload(b'some data')
>>> a.as_string()
TypeError: string payload expected: <class 'bytes'>
它也失败显式使用生成器,并调用 扁平化
。消息正文被转换为 ASCII,应用转义,最后转换为字节进行传输,那么为什么我不能设置字节有效负载呢?
如何获取带有字节有效负载的非 MIME 消息 smtplib.SMTP.send_message
会接受吗?
The following fails:
>>> a = email.message.Message()
>>> a.set_payload(b'some data')
>>> a.as_string()
TypeError: string payload expected: <class 'bytes'>
It also fails using a generator explicitly, and calling flatten
. The message body is converted to ASCII, escapes applied and then finally converted to bytes for transmission anyway, so why can I not set a bytes payload?
How do I go about getting a preferably non-MIME message with a bytes payload that smtplib.SMTP.send_message
will accept?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请记住:在 Python 3 中,字符串都是全部 unicode。您实际上是给 Python 一个 bytes 对象,然后告诉它您想要一个 unicode 字符串,但没有告诉它使用哪种编码将 bytes 对象转换为字符串。
您需要做的是将编码作为第二个参数提供给
set_payload()
调用,如下所示:这确实给出了 MIME 类型消息 - 希望这对您有用。
Remember: in Python 3 strings are all unicode. You are effectively giving Python a bytes object and then telling it you want a unicode string, but not telling it which encoding to use to convert the bytes object to a string.
What you need to do is provide the encoding as the second parameter to the
set_payload()
call, like so:This does give a MIME type message -- hopefully that will work for you.