本文介绍了从Gmail使用Gmail API下载附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在使用Gmail API访问我的Gmail数据和谷歌python api客户端。

I am using Gmail API to access my gmail data and google python api client.

根据获取消息附件的文档,他们给了一个示例python

According to documentation to get the message attachment they gave one sample for python

但我尝试的代码相同然后我收到错误:

but the same code i tried then i am getting error:

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

行我收到错误:

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()

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

but i am not getting part['body']['data'] in for part in message['payload']['parts']

推荐答案

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

Expanding @Eric answer, I wrote the following corrected version of GetAttachments function from the docs:

# 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, prefix=""):
    """Get and store attachment from Message with given id.

    Args:
    service: Authorized Gmail API service instance.
    user_id: User's email address. The special value "me"
    can be used to indicate the authenticated user.
    msg_id: ID of Message containing attachment.
    prefix: prefix which is added to the attachment filename on saving
    """
    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 = prefix+part['filename']

                with open(path, 'w') as f:
                    f.write(file_data)
    except errors.HttpError, error:
        print 'An error occurred: %s' % error

这篇关于从Gmail使用Gmail API下载附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 08:22