我在用邮箱API https://developers.google.com/gmail/api访问我的 Gmail 数据以及谷歌Python API客户端 https://github.com/googleapis/google-api-python-client.
根据文档获取消息依恋他们给了一个sample https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get对于Python。但我尝试了相同的代码,然后出现错误:
AttributeError:“资源”对象没有属性“用户”
我收到错误的行:
message = service.user().messages().get(userId=user_id, id=msg_id).execute()
所以我尝试了users()
通过替换user()
:
message = service.users().messages().get(userId=user_id, id=msg_id).execute()
但我没有得到part['body']['data']
in 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)