gpt4 book ai didi

python - 二进制文件邮件附件问题

转载 作者:太空狗 更新时间:2023-10-29 22:17:14 26 4
gpt4 key购买 nike

使用 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, all_recipients, 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 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 155, in _handle_text
raise TypeError('string payload expected: %s' % type(payload))

最佳答案

来自 this SO answer 的解决方案

from base64 import encodebytes
for file in self.attachments:
fp = open(file, 'rb')
part = MIMEBase('application', "octet-stream")
part.set_payload(encodebytes(fp.read()).decode())
fp.close()
part.add_header('Content-Transfer-Encoding', 'base64')
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())

关于python - 二进制文件邮件附件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2798470/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com