使用 GMAIL 阅读最后 20 条消息 API

Read last 20 messages using GMAIL API

我一直在尝试获取数据以从 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()

更新此代码:

for message in messages:
    msg = service.users().messages().get(userId='me', id=message['id']).execute()
    print (msg['snippet'])

有了这个:

for i, message in enumerate(messages):
    if i == 20:
        break
    msg = service.users().messages().get(userId='me', id=message['id']).execute()
    print (msg['snippet'])

尝试 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', [])

基于@Alderven 和@DalmTo,下面的脚本应该可以工作

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', maxResults=20, 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=label['id']).execute()
            print(msg['snippet'])

if __name__ == '__main__':
    main()