以下是代码(主要来自链接:https://developers.google.com/gmail/api/quickstart/python):
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://mail.google.com/']
def archiveAction(gmail_service):
filter = {
'action': {
'removeLabelIds': ['INBOX']
}
}
result = gmail_service.users().settings().filters().create(userId='me', body=filter).execute()
def archiveAllViaCriteria(gmail_service):
filter = {
'criteria': {
'from': '*'
},
'action': {
'removeLabelIds': ['INBOX']
}
}
result = gmail_service.users().settings().filters().create(userId='me', body=filter).execute()
def printLabels(labels):
if not labels:
print('No labels found.')
else:
print('Labels:')
for label in labels:
print(label['name'])
def getFlowForAlternate():
return InstalledAppFlow.from_client_secrets_file('AlternateAICreds.json', SCOPES)
def getCreds():
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = getFlowForAlternate()
creds = flow.run_local_server()
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
return creds
def getGmailService():
gmail_service = build('gmail', 'v1', credentials=getCreds())
return gmail_service
def printAndArchive():
gmail_service = getGmailService()
results = gmail_service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
print('No labels found.') if not labels else printLabels(labels)
archiveAllViaCriteria(gmail_service)
archiveAction(gmail_service)
我第一次运行此程序时,会看到以下内容
Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=1002988250822-flki6q3ieo90nsj815go8d07d5cufj8d.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&scope=https%3A%2F%2Fmail.google.com%2F&state=H2n7XTW1uVhiYM253y2QNFk21IP7oO&access_type=offline
完成身份验证后,我将看到以下内容
Labels:
CATEGORY_PERSONAL
CATEGORY_SOCIAL
IMPORTANT
CATEGORY_UPDATES
CATEGORY_FORUMS
CHAT
SENT
INBOX
TRASH
CATEGORY_PROMOTIONS
DRAFT
SPAM
STARRED
UNREAD
Traceback (most recent call last):
File "t1.py", line 75, in <module>
gmailUtils.printAndArchive()
File "/Users/AlternateJones/Dropbox/Google Drive/My Software/Ara/python/gmailUtils.py", line 78, in printAndArchive
archiveAllViaCriteria(gmail_service)
File "/Users/AlternateJones/Dropbox/Google Drive/My Software/Ara/python/gmailUtils.py", line 32, in archiveAllViaCriteria
result = gmail_service.users().settings().filters().create(userId='me', body=filter).execute()
File "/Library/Python/2.7/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "/Library/Python/2.7/site-packages/googleapiclient/http.py", line 842, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/gmail/v1/users/me/settings/filters?alt=json returned "Insufficient Permission">
第二次我没有收到提示。
Labels:
CATEGORY_PERSONAL
CATEGORY_SOCIAL
IMPORTANT
CATEGORY_UPDATES
CATEGORY_FORUMS
CHAT
SENT
INBOX
TRASH
CATEGORY_PROMOTIONS
DRAFT
SPAM
STARRED
UNREAD
Traceback (most recent call last):
File "t1.py", line 75, in <module>
gmailUtils.printAndArchive()
File "/Users/AlternateJones/Dropbox/Google Drive/My Software/Ara/python/gmailUtils.py", line 78, in printAndArchive
archiveAllViaCriteria(gmail_service)
File "/Users/AlternateJones/Dropbox/Google Drive/My Software/Ara/python/gmailUtils.py", line 32, in archiveAllViaCriteria
result = gmail_service.users().settings().filters().create(userId='me', body=filter).execute()
File "/Library/Python/2.7/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "/Library/Python/2.7/site-packages/googleapiclient/http.py", line 842, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/gmail/v1/users/me/settings/filters?alt=json returned "Insufficient Permission">
将上面代码中的'userID'从'me'更改为'Ara@Alternate.ai'
Labels:
CATEGORY_PERSONAL
CATEGORY_SOCIAL
IMPORTANT
CATEGORY_UPDATES
CATEGORY_FORUMS
CHAT
SENT
INBOX
TRASH
CATEGORY_PROMOTIONS
DRAFT
SPAM
STARRED
UNREAD
Traceback (most recent call last):
File "t1.py", line 75, in <module>
gmailUtils.printAndArchive()
File "/Users/AlternateJones/Dropbox/Google Drive/My Software/Ara/python/gmailUtils.py", line 78, in printAndArchive
archiveAllViaCriteria(gmail_service)
File "/Users/AlternateJones/Dropbox/Google Drive/My Software/Ara/python/gmailUtils.py", line 32, in archiveAllViaCriteria
result = gmail_service.users().settings().filters().create(userId='Ara@Alternate.ai', body=filter).execute()
File "/Library/Python/2.7/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "/Library/Python/2.7/site-packages/googleapiclient/http.py", line 842, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/gmail/v1/users/Ara%40Alternate.ai/settings/filters?alt=json returned "Insufficient Permission">
仅使用'Ara'作为userId,我看到以下内容,因此很明显'me'和'Ara@Alternate.ai'是有效的'userId',而'Ara'不是。我该如何解决?
Traceback (most recent call last):
File "t1.py", line 75, in <module>
gmailUtils.printAndArchive()
File "/Users/AlternateJones/Dropbox/Google Drive/My Software/Ara/python/gmailUtils.py", line 75, in printAndArchive
results = gmail_service.users().labels().list(userId='Ara').execute()
File "/Library/Python/2.7/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "/Library/Python/2.7/site-packages/googleapiclient/http.py", line 842, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/gmail/v1/users/Ara/labels?alt=json returned "Invalid user id specified in request/Delegation denied">
请注意,我已经在以下链接上授权了此客户端:https://admin.google.com/AdminHome?chromeless=1#OGX:ManageOauthClients
我还验证了token.pickle和creds.json是否存在并且可以访问。