尝试通过API删除Gmail消息时出现401错误

时间:2020-04-03 00:53:36

标签: gmail gmail-api

我从中得到了灵感 https://developers.google.com/gmail/api/quickstart/pythonhttps://developers.google.com/gmail/api/v1/reference/users/labels/list#examples进入以下代码

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 apiclient import errors
import requests as req

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://mail.google.com/']


def chunks(l, n):
    for i in range(0, len(l), n):
        yield l[i:i + n]


def ListMessagesWithLabels(service, user_id, label_ids=[]):
    """List all Messages of the user's mailbox with label_ids applied.

    Args:
      service: Authorized Gmail API service instance.
      user_id: User's email address. The special value "me"
      can be used to indicate the authenticated user.
      label_ids: Only return Messages with these labelIds applied.

    Returns:
      List of Messages that have all required Labels applied. Note that the
      returned list contains Message IDs, you must use get with the
      appropriate id to get the details of a Message.
    """
    try:
        response = service.users().messages().list(userId=user_id,
                                                   labelIds=label_ids).execute()
        messages = []
        if 'messages' in response:
            messages.extend(response['messages'])

        while 'nextPageToken' in response:
            page_token = response['nextPageToken']
            response = service.users().messages().list(userId=user_id,
                                                       labelIds=label_ids,
                                                       pageToken=page_token).execute()
            messages.extend(response['messages'])

        return messages
    except errors.HttpError as error:
        print
        'An error occurred: %s' % error


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(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # 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 (label["id"].upper() != label["id"]):
                messages = ListMessagesWithLabels(service, 'me', [label['id']])
                if messages is not None:
                    usr_id = 'me'
                    ids = [message["id"] for message in messages]
                    for x in chunks(ids, 1000):
                        post_req = req.post(f"https://www.googleapis.com/gmail/v1/users/{usr_id}/messages/batchDelete", data={"ids":x})
                        if post_req.status_code == 200:
                            print("all good")


if __name__ == '__main__':
    main()

目标是遍历每个标签并删除所有消息。 我所有的POST请求都被拒绝,因为即使我启动程序时我也没有获得“授权”,我还是在浏览器中经历了Athentication。

我应该如何构造我的POST才能实现我想做的事情?

1 个答案:

答案 0 :(得分:1)

尝试删除消息时,应使用先前构建的service。这就是您首先进行身份验证的方式。尝试在此处使用batchDelete时:

post_req = req.post(f"https://www.googleapis.com/gmail/v1/users/{usr_id}/messages/batchDelete", data={"ids":x})

您只是对指定端点进行基本请求,没有遵循OAuth流程。另外,由于您没有访问公共资源,因此会遇到授权错误。

您应该改用以下内容:

messagesToDelete = {
  "ids": [
    "messageID1",
    "messageID2",
    # ... rest of messages to delete
  ]
}
service.users().messages().batchDelete(userId="me", body=messagesToDelete).execute()

参考: