Rah*_*ari 14 python email gmail gmail-api
我正在使用Gmail API访问我的Gmail数据和google python api客户端.
根据获取消息附件的文档,他们为python提供了一个示例
https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get
但我尝试相同的代码然后我收到错误:
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()
但我没有part['body']['data']进去for part in message['payload']['parts']
Ily*_*rov 35
扩展@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
您仍然可以按照@Ilya V. Schurov或@Cam T的答案错过附件,原因是基于的电子邮件结构可能有所不同mimeType。
import base64
from apiclient import errors
def GetAttachments(service, user_id, msg_id, store_dir=""):
    """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.
            store_dir: The directory used to store attachments.
    """
    try:
        message = service.users().messages().get(userId=user_id, id=msg_id).execute()
        parts = [message['payload']]
        while parts:
            part = parts.pop()
            if part.get('parts'):
                parts.extend(part['parts'])
            if part.get('filename'):
                if 'data' in part['body']:
                    file_data = base64.urlsafe_b64decode(part['body']['data'].encode('UTF-8'))
                    #self.stdout.write('FileData for %s, %s found! size: %s' % (message['id'], part['filename'], part['size']))
                elif 'attachmentId' in part['body']:
                    attachment = service.users().messages().attachments().get(
                        userId=user_id, messageId=message['id'], id=part['body']['attachmentId']
                    ).execute()
                    file_data = base64.urlsafe_b64decode(attachment['data'].encode('UTF-8'))
                    #self.stdout.write('FileData for %s, %s found! size: %s' % (message['id'], part['filename'], attachment['size']))
                else:
                    file_data = None
                if file_data:
                    #do some staff, e.g.
                    path = ''.join([store_dir, part['filename']])
                    with open(path, 'w') as f:
                        f.write(file_data)
    except errors.HttpError as error:
        print 'An error occurred: %s' % error
我测试了上面的代码,没有用。我为其他帖子更新了一些内容。WriteFileError
    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'].get('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, 'wb') as f:
                f.write(file_data)
        except errors.HttpError as error:
            print('An error occurred: %s' % error)
肯定是的users()。
响应消息的格式很大程度上取决于您使用的格式参数。如果您使用默认值 (FULL),则部件将具有part['body']['data']或者,当数据较大时,具有attachment_id可传递给 的字段messages().attachments().get()。
如果您查看附件文档,您会看到以下内容: https: //developers.google.com/gmail/api/v1/reference/users/messages/attachments
(如果主消息文档页面也提到了这一点,那就太好了。)
| 归档时间: | 
 | 
| 查看次数: | 13107 次 | 
| 最近记录: |