首页 > 解决方案 > 使用 gmail API 从 oauth2.googleapis.com 获取令牌时出错

问题描述

我一直在尝试制作一个使用 gmails API 发送电子邮件的简单程序(所以我希望不需要启用“不太安全的应用程序”)。但是,我在测试时开始遇到错误。

Traceback (most recent call last):
  File "C:\Users\<me>\Desktop\Python code\Email\email - 1.1\gmailAPI.py", line 51, in <module>
    main()
  File "C:\Users\<me>\Desktop\Python code\Email\email - 1.1\gmailAPI.py", line 32, in main
    creds = flow.run_local_server()
  File "C:\Python3.7\lib\site-packages\google_auth_oauthlib\flow.py", line 442, in run_local_server
    self.fetch_token(authorization_response=authorization_response)
  File "C:\Python3.7\lib\site-packages\google_auth_oauthlib\flow.py", line 263, in fetch_token
    self.client_config['token_uri'], **kwargs)
  File "C:\Python3.7\lib\site-packages\requests_oauthlib\oauth2_session.py", line 284, in fetch_token
    verify=verify, proxies=proxies)
  File "C:\Python3.7\lib\site-packages\requests\sessions.py", line 581, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "C:\Python3.7\lib\site-packages\requests_oauthlib\oauth2_session.py", line 425, in request
    headers=headers, data=data, **kwargs)
  File "C:\Python3.7\lib\site-packages\requests\sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Python3.7\lib\site-packages\requests\sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "C:\Python3.7\lib\site-packages\requests\adapters.py", line 510, in send
    raise ProxyError(e, request=request)
requests.exceptions.ProxyError: HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Max retries exceeded with url: /token (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden')))

我很确定这与在我的测试中发送太多请求有关。但是,我需要克服这个问题,这样我才能继续弄清楚如何使用和操作 API。

这是我用来测试 Gmail API 的。它基本上只是 python 快速入门。

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from time import sleep

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = None
    # The file token.pickle 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.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # 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(
                "client_secret.json", SCOPES)
            sleep(1)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)

    # Call the Gmail API
    results = service.users().labels().list(userId='me').execute()
    labels = results.get('labels', [])

    if not labels:
        print('No labels found.')
    else:
        print('Labels:')
        for label in labels:
            print(label['name'])

if __name__ == '__main__':
    main()

标签: python-3.xgmail-api

解决方案


我认为您在此SO 帖子中遇到了同样的错误。请使用 . 检查您的格式message.get

message = service.users().messages().get(userId=user_id, id=msg_id,
                                         format='raw').execute()

print 'Message snippet: %s' % message['snippet']

msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))

mime_msg = email.message_from_string(msg_str)

推荐阅读