admin管理员组

文章数量:1126367

I have tried to access gmail through the google oauth2 client. However I cannot seem to make it work:

def readEmails():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                # your creds file here. Please create json file as here 
                credential_path, SCOPES)
            creds = flow.run_local_server(port=4000)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    try:
        # Call the Gmail API
        service = build('gmail', 'v1', credentials=creds)
        results = service.users().messages().list(userId='me', labelIds=['INBOX'], q="is:unread").execute()
        messages = results.get('messages',[]);
        if not messages:
            print('No new messages.')
        else:
            print('would read')
            return
    except Exception as error:
        print(f'An error occurred: {error}')

It runs fine for the first run, getting all the information I wish. However the second run, where it would read the token file it gives the error:

ValueError: Authorized user info was not in the expected format, missing fields refresh_token.

if I look into the json I indeed do not see any refresh token part of the json.

I notice this already happens in the "from_authorized_user_file", indeed the refresh token isn't even sent initially.

本文标签: pythonGoogle credentials not getting a refresh tokenStack Overflow