Gmail Api Python:删除功能不起作用
Gmail Api Python: function delete not working
我在 2 个日期之间得到了我的消息的 ID,但是在我的程序中不可能通过它们的 ID 删除这些消息。
因为我总是在我的异常代码 "erreur suppression" 中。
我已经在 "Try api" 中使用相同的设置进行了测试,它可以工作:https://developers.google.com/gmail/api/v1/reference/users/messages/delete?apix_params=%7B%22userId%22%3A%22me%22%2C%22id%22%3A%2216be66c1f679ceee%22%7D#auth
content的类型是string,id的类型也一样api。
我用的是这个方法:https://developers.google.com/gmail/api/quickstart/python
下面是有用的代码:
# -*- coding: utf-8 -*-
from __future__ import print_function
from datetime import date, timedelta, datetime
import pickle
import os.path
import time
import datetime
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from apiclient import errors
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def main():
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('credentials.json', SCOPES)
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)
debut = input("Entrez la date de début de supression des messages au fomat JJ/MM/AAAA : ")
fin = input("Entrez la date de fin de supression des messages au format JJ/MM/AAAA : ")
ts_debut = time.mktime(datetime.datetime.strptime(debut, "%d/%m/%Y").timetuple())
ts_fin = time.mktime(datetime.datetime.strptime(fin, "%d/%m/%Y").timetuple())
debut = int(ts_debut)
fin = int(ts_fin)
query = 'after:' + str(debut) + 'AND before:' + str(fin)
results = service.users().messages().list(userId='me', labelIds=['INBOX'], q=query).execute()
# Call the Gmail API
messages = results.get('messages', [])
user_id = 'user email address'
if not messages:
print('No labels found.')
# Dates have to formatted in YYYY/MM/DD format for gmailelse:
print('Labels:')
for messages in messages:
content = messages['id']
try:
message = service.users().messages().get(userId='me', id=content, format='metadata').execute()
try:
service.users().messages().delete(userId=user_id, id=content).execute()
print("")
except errors.HttpError:
print ("erreur")
print(content)
except:
print('erreur date')
main()
我找到了答案,我的范围是错误的:gmail.readonly 更改为 https://mail.google.com/ 以获得对帐户的完全访问权限,包括永久删除线程和消息。
转到此 link 了解更多信息:https://developers.google.com/gmail/api/auth/scopes
我在 2 个日期之间得到了我的消息的 ID,但是在我的程序中不可能通过它们的 ID 删除这些消息。 因为我总是在我的异常代码 "erreur suppression" 中。
我已经在 "Try api" 中使用相同的设置进行了测试,它可以工作:https://developers.google.com/gmail/api/v1/reference/users/messages/delete?apix_params=%7B%22userId%22%3A%22me%22%2C%22id%22%3A%2216be66c1f679ceee%22%7D#auth
content的类型是string,id的类型也一样api。
我用的是这个方法:https://developers.google.com/gmail/api/quickstart/python
下面是有用的代码:
# -*- coding: utf-8 -*-
from __future__ import print_function
from datetime import date, timedelta, datetime
import pickle
import os.path
import time
import datetime
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from apiclient import errors
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def main():
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('credentials.json', SCOPES)
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)
debut = input("Entrez la date de début de supression des messages au fomat JJ/MM/AAAA : ")
fin = input("Entrez la date de fin de supression des messages au format JJ/MM/AAAA : ")
ts_debut = time.mktime(datetime.datetime.strptime(debut, "%d/%m/%Y").timetuple())
ts_fin = time.mktime(datetime.datetime.strptime(fin, "%d/%m/%Y").timetuple())
debut = int(ts_debut)
fin = int(ts_fin)
query = 'after:' + str(debut) + 'AND before:' + str(fin)
results = service.users().messages().list(userId='me', labelIds=['INBOX'], q=query).execute()
# Call the Gmail API
messages = results.get('messages', [])
user_id = 'user email address'
if not messages:
print('No labels found.')
# Dates have to formatted in YYYY/MM/DD format for gmailelse:
print('Labels:')
for messages in messages:
content = messages['id']
try:
message = service.users().messages().get(userId='me', id=content, format='metadata').execute()
try:
service.users().messages().delete(userId=user_id, id=content).execute()
print("")
except errors.HttpError:
print ("erreur")
print(content)
except:
print('erreur date')
main()
我找到了答案,我的范围是错误的:gmail.readonly 更改为 https://mail.google.com/ 以获得对帐户的完全访问权限,包括永久删除线程和消息。
转到此 link 了解更多信息:https://developers.google.com/gmail/api/auth/scopes