python-3.x - 使用 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()
解决方案
我认为您在此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)
推荐阅读
- android - OutputStream.write(byte[] bytes) 给出 NetworkOnMainThread 异常但我没有在主线程上使用此方法
- kubernetes - 持续部署气流 dag
- python - 如何将我的 opencv 相机广播到假相机上?
- powerbi-desktop - 如何过滤 PowerBI 中所有设置的过滤器的集中?
- c# - C# js Append 版本也适用于导入中使用的文件
- php - 无法对属性“publishedAt”值进行非规范化
- email - Microsoft Graph Api {"code":"ErrorInvalidPropertySet","message":"设置操作对属性无效。"}
- regex - .htaccess url 重写特定的 url
- php - Laravel 组件元素
- pandas - 熊猫在方法链中分配列名