Skip to main content
 首页 » 编程设计

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

2024年12月31日11tuyile006

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