我在2个日期之间获得了消息的ID,但是无法在程序中通过消息的ID删除此消息。 因为我总是在异常代码“错误抑制”中进行操作。
我已经在“ 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
内容类型是字符串,也类似于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()
答案 0 :(得分:0)
我找到了答案,我的范围是错误的:gmail.readonly更改为https://mail.google.com/,以完全访问该帐户,包括永久删除线程和消息。
转到此链接以获取更多信息:https://developers.google.com/gmail/api/auth/scopes