列出 Gmail 邮件
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
本页介绍了如何调用 Gmail API 的 users.messages.list
方法。
该方法会返回一个 Gmail Message
资源数组,其中包含消息 id
和 threadId
。如需检索完整的消息详细信息,请使用 users.messages.get
方法。
前提条件
列出消息
users.messages.list
方法支持多个查询参数来过滤消息:
maxResults
:要返回的消息数上限(默认值为 100,上限为 500)。
pageToken
:用于检索特定页面的结果的令牌。
q
:用于过滤消息的查询字符串,例如 from:someuser@example.com is:unread"
。
labelIds
:仅返回标签与所有指定标签 ID 都匹配的消息。
includeSpamTrash
:在结果中包含来自 SPAM
和 TRASH
的消息。
代码示例
Python
以下代码示例展示了如何列出经过身份验证的 Gmail 用户的邮件。该代码会处理分页,以检索与查询匹配的所有消息。
users.messages.list
方法返回的响应正文包含以下内容:
messages[]
:Message
资源的数组。
nextPageToken
:对于包含多页结果的请求,此令牌可用于后续调用以列出更多消息。
resultSizeEstimate
:估计的总结果数。
如需提取完整的消息内容和元数据,请使用 message.id
字段调用 users.messages.get
方法。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-01。
[null,null,["最后更新时间 (UTC):2025-08-01。"],[],[],null,["# List Gmail messages\n\nThis page explains how to call the Gmail API's\n[`users.messages.list`](/workspace/gmail/api/reference/rest/v1/users.messages/list)\nmethod.\n\nThe method returns an array of Gmail `Message` resources that\ncontain the message `id` and `threadId`. To retrieve full message details, use\nthe\n[`users.messages.get`](/workspace/gmail/api/reference/rest/v1/users.messages/get)\nmethod.\n\nPrerequisites\n-------------\n\n### Python\n\nA Google Cloud project with the Gmail API enabled. For steps, complete\nthe\n[Gmail API Python quickstart](/workspace/gmail/api/quickstart/python).\n\nList messages\n-------------\n\nThe `users.messages.list` method supports several query parameters to filter the\nmessages:\n\n- `maxResults`: Maximum number of messages to return (defaults to 100, max 500).\n- `pageToken`: Token to retrieve a specific page of results.\n- `q`: Query string to filter messages, such as `from:someuser@example.com is:unread\"`.\n- `labelIds`: Only return messages with labels that match all specified label IDs.\n- `includeSpamTrash`: Include messages from `SPAM` and `TRASH` in the results.\n\n### Code sample\n\n### Python\n\nThe following code sample shows how to list messages for the authenticated\nGmail user. The code handles pagination to retrieve all\nmessages matching the query. \ngmail/snippet/list_messages.py \n[View on GitHub](https://github.com/googleworkspace/python-samples/blob/main/gmail/snippet/list_messages.py) \n\n```python\nimport os.path\nfrom google.auth.transport.requests import Request\nfrom google.oauth2.credentials import Credentials\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\n\n# If modifying these scopes, delete the file token.json.\nSCOPES = [\"https://www.googleapis.com/auth/gmail.readonly\"]\n\n\ndef main():\n \"\"\"Shows basic usage of the Gmail API.\n Lists the user's Gmail messages.\n \"\"\"\n creds = None\n # The file token.json stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists(\"token.json\"):\n creds = Credentials.from_authorized_user_file(\"token.json\", SCOPES)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\"credentials.json\", SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open(\"token.json\", \"w\") as token:\n token.write(creds.to_json())\n\n try:\n # Call the Gmail API\n service = build(\"gmail\", \"v1\", credentials=creds)\n results = (\n service.users().messages().list(userId=\"me\", labelIds=[\"INBOX\"]).execute()\n )\n messages = results.get(\"messages\", [])\n\n if not messages:\n print(\"No messages found.\")\n return\n\n print(\"Messages:\")\n for message in messages:\n print(f'Message ID: {message[\"id\"]}')\n msg = (\n service.users().messages().get(userId=\"me\", id=message[\"id\"]).execute()\n )\n print(f' Subject: {msg[\"snippet\"]}')\n\n except HttpError as error:\n # TODO(developer) - Handle errors from gmail API.\n print(f\"An error occurred: {error}\")\n\n\nif __name__ == \"__main__\":\n main()\n```\n\nThe `users.messages.list` method returns a response body that contains the\nfollowing:\n\n- `messages[]`: An array of `Message` resources.\n- `nextPageToken`: For requests with multiple pages of results, a token that can be used with a subsequent calls to list more messages.\n- `resultSizeEstimate`: An estimated total number of results.\n\nTo fetch the full message content and metadata, use the `message.id` field to\ncall the\n[`users.messages.get`](/workspace/gmail/api/reference/rest/v1/users.messages/get)\nmethod.\n\nRelated resources\n-----------------\n\n- [`users.messages.list`](/workspace/gmail/api/reference/rest/v1/users.messages/list)\n- [`users.messages.get`](/workspace/gmail/api/reference/rest/v1/users.messages/get)"]]