首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >尝试通过API删除gmail消息时出现401错误

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

Stack Overflow用户
提问于 2020-04-03 00:53:36
回答 1查看 211关注 0票数 0

我从https://developers.google.com/gmail/api/quickstart/pythonhttps://developers.google.com/gmail/api/v1/reference/users/labels/list#examples那里得到灵感,可以得到下面的代码

代码语言:javascript
运行
复制
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()

目标是遍历每个标签并删除所有消息。我所有的帖子请求都被拒绝了,因为我没有“授权”,即使当我启动程序的时候,我会在浏览器中通过雅典,等等。

我应该如何构建我的职位才能实现我想要做的事情?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-03 08:35:49

当尝试删除消息时,您应该使用以前构建的service。你一开始就是这么鉴定的。在这里尝试使用batchDelete时:

代码语言:javascript
运行
复制
post_req = req.post(f"https://www.googleapis.com/gmail/v1/users/{usr_id}/messages/batchDelete", data={"ids":x})

您只是对指定的端点执行基本请求,而不是遵循OAuth过程。而且,由于您没有访问公共资源,所以您将得到一个授权错误。

您应该使用以下内容:

代码语言:javascript
运行
复制
messagesToDelete = {
  "ids": [
    "messageID1",
    "messageID2",
    # ... rest of messages to delete
  ]
}
service.users().messages().batchDelete(userId="me", body=messagesToDelete).execute()

参考资料:

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61003514

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档