如何解决二进制文件电子邮件附件问题
好的-经过无奈和网上搜索后,我发现问题是一个已知的错误,适用于Python 3.x,encoders.py,encode_base64函数,其内容应如下所示…
def encode_base64(msg):
"""Encode the message's payload in Base64.
Also, add an appropriate Content-transfer-encoding header.
"""
orig = msg.get_payload()
encdata = _bencode(orig)
# new line inserted to ensure all bytes characters are converted to ASCII
encdata = str(encdata, "ASCII")
msg.set_payload(encdata)
msg['Content-transfer-encoding'] = 'base64'
该错误已作为问题#4768提出,并于2010-05-10升级为严重状态。希望它将在下一版本(3.1.3?)中修复。
问候,艾伦
解决方法
使用Python 3.1.2,我在发送二进制附件文件(jpeg,pdf等)时遇到问题-MIMEText附件可以正常工作。有问题的代码如下…
for file in self.attachments:
part = MIMEBase('application',"octet-stream")
part.set_payload(open(file,"rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition','attachment; filename="%s"' % file)
msg.attach(part) # msg is an instance of MIMEMultipart()
server = smtplib.SMTP(host,port)
server.login(username,password)
server.sendmail(from_addr,all_recipients,msg.as_string())
但是,在调用堆栈的最下方(请参见下面的回溯),看起来msg.as_string()已接收到一个附件,该附件创建了“字节”类型的有效负载而不是字符串。
有谁知道是什么原因引起的问题?任何帮助,将不胜感激。
艾伦
builtins.TypeError: string payload expected: <class 'bytes'>
File "c:\Dev\CommonPY\Scripts\email_send.py",line 147,in send
server.sendmail(self.from_addr,msg.as_string())
File "c:\Program Files\Python31\Lib\email\message.py",line 136,in as_string
g.flatten(self,unixfrom=unixfrom)
File "c:\Program Files\Python31\Lib\email\generator.py",line 76,in flatten
self._write(msg)
File "c:\Program Files\Python31\Lib\email\generator.py",line 101,in _write
self._dispatch(msg)
File "c:\Program Files\Python31\Lib\email\generator.py",line 127,in _dispatch
meth(msg)
File "c:\Program Files\Python31\Lib\email\generator.py",line 181,in _handle_multipart
g.flatten(part,unixfrom=False)
File "c:\Program Files\Python31\Lib\email\generator.py",line 155,in _handle_text
raise TypeError('string payload expected: %s' % type(payload))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。