gpt4 book ai didi

python - 使用 Gmail API 从 Gmail 下载附件

转载 作者:太空狗 更新时间:2023-10-29 17:21:19 28 4
gpt4 key购买 nike

我正在使用 Gmail API访问我的 Gmail 数据和 Google Python API client .

根据文档获取消息附件,他们给了一个sample对于 Python。但是我尝试使用相同的代码然后出现错误:

AttributeError: 'Resource' object has no attribute 'user'

出现错误的行:

message = service.user().messages().get(userId=user_id, id=msg_id).execute()

所以我通过替换 user() 来尝试 users():

message = service.users().messages().get(userId=user_id, id=msg_id).execute()

但是我没有在中得到part['body']['data'] for part in message['payload']['parts']

最佳答案

扩展@Eric 的答案,我从文档中编写了以下更正版本的 GetAttachments 函数:

# based on Python example from 
# https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get
# which is licensed under Apache 2.0 License

import base64
from apiclient import errors

def GetAttachments(service, user_id, msg_id):
"""Get and store attachment from Message with given id.

:param service: Authorized Gmail API service instance.
:param user_id: User's email address. The special value "me" can be used to indicate the authenticated user.
:param msg_id: ID of Message containing attachment.
"""
try:
message = service.users().messages().get(userId=user_id, id=msg_id).execute()

for part in message['payload']['parts']:
if part['filename']:
if 'data' in part['body']:
data = part['body']['data']
else:
att_id = part['body']['attachmentId']
att = service.users().messages().attachments().get(userId=user_id, messageId=msg_id,id=att_id).execute()
data = att['data']
file_data = base64.urlsafe_b64decode(data.encode('UTF-8'))
path = part['filename']

with open(path, 'w') as f:
f.write(file_data)

except errors.HttpError, error:
print 'An error occurred: %s' % error

关于python - 使用 Gmail API 从 Gmail 下载附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25832631/

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