尽管给出了完整的邮件范围,为什么我仍然收到权限不足错误?

时间:2018-12-11 18:34:58

标签: python-3.x gmail-api

import httplib2
import os
import oauth2client
from oauth2client import client, tools
from apiclient import errors, discovery

SCOPES = 'https://mail.google.com/'

APPLICATION_NAME = 'Gmail API Python List Email'
CLIENT_SECRET_FILE = 'client_secret_ishandutta2007.json'# This file will be in local dir
CREDENTIAL_FILE_NAME = 'gmail-python-email-send_ishandutta2007.json'

def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, CREDENTIAL_FILE_NAME)
    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        credentials = tools.run_flow(flow, store)
        print(('Storing credentials to ' + credential_path))
    return credentials


def ListMessagesMatchingQuery(service, user_id, query=''):
    try:
        response = service.users().messages().list(userId=user_id, q=query).execute()
        messages = []
        if 'messages' in response:
            messages.extend(response['messages'])

        while 'nextPageToken' in response:
            page_token = response['nextPageToken']
            response = service.users().messages().list(userId=user_id, q=query,
                                                pageToken=page_token).execute()
            messages.extend(response['messages'])

        return messages
    except errors.HttpError as error:
        print('An error occurred: %s' % error)

def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)
    ListMessagesMatchingQuery(service, "me", query="senior recruit")


if __name__ == '__main__':
    main()
  

发生错误:https://www.googleapis.com/gmail/v1/users/me/messages?q=senior+recruit&alt=json   返回“权限不足”

1 个答案:

答案 0 :(得分:1)

发现了问题,在上面的代码中是从文件gmail-python-email-send_ishandutta2007.json中提取了一个缓存的凭据,该文件仅允许发送邮件,将此文件名更改为新的名称即可解决该问题。