使用gmail API从oauth2.googleapis.com获取令牌时出错

时间:2019-06-20 08:22:52

标签: python-3.x gmail-api

我一直在尝试制作一个简单的程序,该程序使用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 quckstart。

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

1 个答案:

答案 0 :(得分:0)

我认为您与此SO post有同样的错误。请使用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)