gpt4 book ai didi

python - 使用 GMAIL API 阅读最近 20 条消息

转载 作者:太空宇宙 更新时间:2023-11-04 04:22:43 25 4
gpt4 key购买 nike

我一直在尝试获取数据以从 Gmail API 读取邮件。

它工作正常,但如何限制此代码仅获取最后 20 条消息。不是所有的消息。

from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'

def main():

store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('gmail', 'v1', http=creds.authorize(Http()))

# Call the Gmail API to fetch INBOX
results = service.users().messages().list(userId='me', labelIds=['INBOX']).execute()
messages = results.get('messages', [])

if not messages:
print("No messages found.")
else:
print("Message snippets:")
for message in messages:
msg = service.users().messages().get(userId='me', id=message['id']).execute()
print(msg['snippet'])

if __name__ == '__main__':
main()

编辑:

只需在调用 GMAIL API 获取收件箱时添加此添加即可。

results = service.users().messages().list(userId='me',maxResults=20,labelIds = ['INBOX']).execute()

最佳答案

尝试使用 google API 提供的分页概念来限制响应中返回的消息。这里是官方Documentation

Some API methods may return very large lists of data. To reduce the response size, many of these API methods support pagination. With paginated results, your application can iteratively request and process large lists one page at a time. For API methods that support it, there exist similarly named methods with a "_next" suffix. For example, if a method is named list(), there may also be a method named list_next().

你必须做的
messages = results.get_next('messages', [])

关于python - 使用 GMAIL API 阅读最近 20 条消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54140803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com