管理线程
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
Gmail API 使用 Thread
资源将电子邮件回复及其原始邮件归为单个会话或话题。这样一来,您就可以按顺序检索对话中的所有消息,从而更轻松地了解消息的上下文或优化搜索结果。
与邮件一样,主题也可以应用标签。不过,与消息不同的是,您无法创建帖子串,只能删除帖子串。不过,消息可以插入到消息串中。
目录
检索线程
线程提供了一种简单的方法,用于按顺序检索对话中的消息。
通过列出一组线程,您可以选择按对话对消息进行分组,并提供更多上下文。您可以使用 threads.list
方法检索线程列表,也可以使用 threads.get
检索特定线程。您还可以使用与 Message
资源相同的查询参数来过滤线程。如果会话中的任何邮件与查询匹配,则该会话会返回在结果中。
以下代码示例演示了如何在显示收件箱中最活跃的对话串的示例中使用这两种方法。threads.list
方法会提取所有线程 ID,然后 threads.get
会抓取每个线程中的所有消息。对于回复数达到 3 条或更多条的对话,我们会提取 Subject
行,并显示非空行以及对话中的消息数量。您还可以在相应的 DevByte 视频中找到此代码示例。
向对话串添加草稿和消息
如果您要发送或迁移的邮件是对另一封电子邮件的回复,或者属于某个对话的一部分,那么您的应用应将该邮件添加到相关线程。这样一来,参与对话的 Gmail 用户就能更轻松地了解消息的上下文。
在创建、更新或发送草稿邮件时,可以将草稿添加到线程中。
您还可以在插入或发送消息时向线程添加消息。
如需成为对话串的一部分,邮件或草稿必须满足以下条件:
- 您在请求中提供的
Message
或 Draft.Message
上必须指定所请求的 threadId
。
- 必须根据 RFC 2822 标准设置
References
和 In-Reply-To
标头。
Subject
标头必须一致。
不妨看看创建草稿或发送消息示例。在这两种情况下,您只需将与线程 ID 配对的 threadId
键添加到消息的元数据(即 message
对象)中。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-29。
[null,null,["最后更新时间 (UTC):2025-08-29。"],[],[],null,["# Managing Threads\n\nThe Gmail API uses [`Thread` resources](/workspace/gmail/api/v1/reference/users/threads)\nto group email replies with their original message into a single conversation or\nthread. This allows you to retrieve all messages in a conversation, in order,\nmaking it easier to have context for a message or to refine search results.\n\nLike [messages](/workspace/gmail/api/v1/reference/users/messages), threads may also have\nlabels applied to them. However, unlike messages, threads cannot be created,\nonly deleted. Messages can, however, be inserted into a thread.\n\nContents\n--------\n\nRetrieving threads\n------------------\n\nThreads provide a simple way of retrieving messages in a conversation in order.\nBy listing a set of threads you can choose to group messages by conversation\nand provide additional context. You can retrieve a list of threads using the\n[`threads.list`](/workspace/gmail/api/v1/reference/users/threads/list) method, or retrieve\na specific thread with\n[`threads.get`](/workspace/gmail/api/v1/reference/users/threads/list). You can also\n[filter threads](/workspace/gmail/api/guides/filtering) using the same query parameters as\nfor the [`Message` resource](/workspace/gmail/api/v1/reference/users/messages). If any\nmessage in a thread matches the query, that thread is returned in the result. \n\nThe code sample below demonstrates how to use both methods in a sample that\ndisplays the most chatty threads in your inbox. The `threads.list` method\nfetches all thread IDs, then `threads.get` grabs all messages in each thread.\nFor those with 3 or more replies, we extract the `Subject` line and display the\nnon-empty ones plus the number of messages in the thread. You'll also find this\ncode sample featured in the corresponding DevByte video.\n\n### Python\n\ngmail/snippet/thread/threads.py \n[View on GitHub](https://github.com/googleworkspace/python-samples/blob/main/gmail/snippet/thread/threads.py) \n\n```python\nimport google.auth\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\n\n\ndef show_chatty_threads():\n \"\"\"Display threads with long conversations(\u003e= 3 messages)\n Return: None\n\n Load pre-authorized user credentials from the environment.\n TODO(developer) - See https://developers.google.com/identity\n for guides on implementing OAuth2 for the application.\n \"\"\"\n creds, _ = google.auth.default()\n\n try:\n # create gmail api client\n service = build(\"gmail\", \"v1\", credentials=creds)\n\n # pylint: disable=maybe-no-member\n # pylint: disable:R1710\n threads = (\n service.users().threads().list(userId=\"me\").execute().get(\"threads\", [])\n )\n for thread in threads:\n tdata = (\n service.users().threads().get(userId=\"me\", id=thread[\"id\"]).execute()\n )\n nmsgs = len(tdata[\"messages\"])\n\n # skip if \u003c3 msgs in thread\n if nmsgs \u003e 2:\n msg = tdata[\"messages\"][0][\"payload\"]\n subject = \"\"\n for header in msg[\"headers\"]:\n if header[\"name\"] == \"Subject\":\n subject = header[\"value\"]\n break\n if subject: # skip if no Subject line\n print(f\"- {subject}, {nmsgs}\")\n return threads\n\n except HttpError as error:\n print(f\"An error occurred: {error}\")\n\n\nif __name__ == \"__main__\":\n show_chatty_threads()\n```\n\nAdding drafts and messages to threads\n-------------------------------------\n\nIf you are sending or migrating messages that are a response to another email\nor part of a conversation, your application should add that message to the\nrelated thread. This makes it easier for Gmail users who are participating in\nthe conversation to keep the message in context.\n\nA draft can be added to a thread as part of\n[creating](/workspace/gmail/api/v1/reference/users/drafts/create),\n[updating](/workspace/gmail/api/v1/reference/users/drafts/update), or\n[sending](/workspace/gmail/api/v1/reference/users/drafts/send) a draft message.\nYou can also add a message to a thread as part of\n[inserting](/workspace/gmail/api/v1/reference/users/messages/insert) or\n[sending](/workspace/gmail/api/v1/reference/users/messages/send) a message.\n\nIn order to be part of a thread, a message or draft must meet the following\ncriteria:\n\n1. The requested `threadId` must be specified on the `Message` or `Draft.Message` you supply with your request.\n2. The `References` and `In-Reply-To` headers must be set in compliance with the [RFC 2822](https://tools.ietf.org/html/rfc2822#appendix-A.2) standard.\n3. The `Subject` headers must match.\n\nTake a look at the [creating a draft](/workspace/gmail/api/guides/drafts) or [sending a\nmessage](/workspace/gmail/api/guides/sending) examples. In both cases, you would simply\nadd a `threadId` key paired with a thread ID to a message's metadata, the\n`message` object."]]