感谢@prisoner 和gmail 的 api tester,我能够让我的 Python 版本正常工作。
我从“quickstart.py”示例开始,并克服了所有 oauth 障碍以使该代码运行。要让quickstart.py 正常工作,需要找到Rachel Hadad 的评论才能让我的凭据正常运行。Google 的文档将凭据视为一个小问题,但对我来说,这是让他们的示例运行的关键。
运行 Google 的示例代码后,我对其进行了如下所示的修改,以使用创建语法的两种变体在我的 gmail 帐户中创建名为“nood”和“foob”的新标签。花费了太多的阅读和精力来弄清楚要使用的正确语法是什么。也许这个“semiquickstart.py”会帮助像我这样发现 Google 文档几乎不透明的人。
from __future__ import print_function
import os
import os.path
import sys
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
import json
import requests
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/gmail.labels']
def main():
"""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(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
service = build('gmail', 'v1', credentials=creds)
label={
"labelListVisibility": "labelShow",
"messageListVisibility": "show",
"name": "nood"
}
results = service.users().labels().create(userId='me',body={'labelListVisibility' : 'labelShow', 'messageListVisibility' : 'show', 'name' : 'foob'}).execute()
print(results)
results = service.users().labels().create(userId='me',body=label).execute()
print(results)
if __name__ == '__main__':
main()