列出 Gmail 邮件

本页介绍了如何调用 Gmail API 的 users.messages.list 方法。

该方法会返回一个 Gmail Message 资源数组,其中包含消息 idthreadId。如需检索完整的消息详细信息,请使用 users.messages.get 方法。

前提条件

Python

启用了 Gmail API 的 Google Cloud 项目。如需了解相关步骤,请完成 Gmail API Python 快速入门

列出消息

users.messages.list 方法支持多个查询参数来过滤消息:

  • maxResults:要返回的消息数上限(默认值为 100,上限为 500)。
  • pageToken:用于检索特定页面的结果的令牌。
  • q:用于过滤消息的查询字符串,例如 from:someuser@example.com is:unread"
  • labelIds:仅返回标签与所有指定标签 ID 都匹配的消息。
  • includeSpamTrash:在结果中包含来自 SPAMTRASH 的消息。

代码示例

Python

以下代码示例展示了如何列出经过身份验证的 Gmail 用户的邮件。该代码会处理分页,以检索与查询匹配的所有消息。

gmail/snippet/list_messages.py
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]


def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail messages.
    """
    creds = None
    # The file token.json 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.json"):
        creds = Credentials.from_authorized_user_file("token.json", SCOPES)
    # 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.json", "w") as token:
            token.write(creds.to_json())

    try:
        # Call the Gmail API
        service = build("gmail", "v1", credentials=creds)
        results = (
            service.users().messages().list(userId="me", labelIds=["INBOX"]).execute()
        )
        messages = results.get("messages", [])

        if not messages:
            print("No messages found.")
            return

        print("Messages:")
        for message in messages:
            print(f'Message ID: {message["id"]}')
            msg = (
                service.users().messages().get(userId="me", id=message["id"]).execute()
            )
            print(f'  Subject: {msg["snippet"]}')

    except HttpError as error:
        # TODO(developer) - Handle errors from gmail API.
        print(f"An error occurred: {error}")


if __name__ == "__main__":
    main()

users.messages.list 方法返回的响应正文包含以下内容:

  • messages[]Message 资源的数组。
  • nextPageToken:对于包含多页结果的请求,此令牌可用于后续调用以列出更多消息。
  • resultSizeEstimate:估计的总结果数。

如需提取完整的消息内容和元数据,请使用 message.id 字段调用 users.messages.get 方法。