我有包含附件的邮件。
我需要上传附件从邮件到谷歌驱动器。
对于邮件,我使用的是[医]阿帕普利b,对于谷歌驱动器,我使用的是pyDrive
我使用下面的代码获取附件:
if mail.get_content_maintype() == 'multipart':
for part in mail.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
attachment = part.get_payload(decode=True)我有payload的附件在邮件中。现在我不明白如何使用payload将pyDrive上传到谷歌驱动器。我试过了,但没有用
attachment = part.get_payload(decode=True)
gd_file = self.gd_box.g_drive.CreateFile({'title': 'Hello.jpg',
"parents": [{"kind": "drive#fileLink", "id": folder['id']}]})
gd_file.GetContentFile(attachment)
gd_file.Upload()UPD:
这段代码是可行的,但我认为它的解决方案很糟糕(我们在本地保存图像,然后将图像上传到google驱动器中)
attachment = part.get_payload(decode=True)
att_path = os.path.join("", part.get_filename())
if not os.path.isfile(att_path):
fp = open(att_path, 'wb')
fp.write(attachment)
fp.close()
gd_file = self.gd_box.g_drive.CreateFile({'title': part.get_filename(),
"parents": [{"kind": "drive#fileLink", "id": folder['id']}]})
gd_file.SetContentFile(part.get_filename())
gd_file.Upload()发布于 2018-01-21 11:02:27
GetContentFile()用于将GoogleDriveFile保存到本地文件。相反,请尝试使用SetContentString(),然后调用Upload()
gd_file.SetContentString(attachment)
gd_file.Upload()更新
如果您正在处理二进制数据(如图像文件中包含的数据),SetContentString()将无法工作。作为一项工作,您可以将数据写入临时文件,上传到驱动器,然后删除临时文件:
import os
from tempfile import NamedTemporaryFile
tmp_name = None
with NamedTemporaryFile(delete=False) as tf:
tf.write(part.get_payload(decode=True))
tmp_name = tf.name # save the file name
if tmp_name is not None:
gd_file.SetContentFile(tf_name)
gd_file.Upload()
os.remove(tmp_name)https://stackoverflow.com/questions/48365925
复制相似问题