管理執行緒
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
Gmail API 會使用Thread
資源,將電子郵件回覆與原始郵件歸到同一個會話群組或會話串。這項功能可讓您依序擷取對話中的所有訊息,方便您瞭解訊息的來龍去脈,或縮小搜尋範圍。
與訊息一樣,討論串也可以套用標籤。不過,與訊息不同的是,您無法建立討論串,只能刪除討論串。不過,訊息可以插入對話串。
目錄
正在擷取執行緒
討論串可讓您輕鬆依序擷取對話中的訊息。
列出多個執行緒後,您可以選擇依對話分組訊息,並提供額外背景資訊。您可以使用 threads.list
方法擷取執行緒清單,或使用 threads.get
擷取特定執行緒。您也可以使用與 Message
資源相同的查詢參數篩選執行緒。如果討論串中的任何訊息符合查詢條件,該討論串就會顯示在結果中。
下方的程式碼範例示範如何在範例中使用這兩種方法,顯示收件匣中最熱門的討論串。threads.list
方法會擷取所有討論串 ID,然後 threads.get
擷取每個討論串中的所有訊息。如果回覆超過 3 則,我們會擷取 Subject
行,並顯示非空白的行,以及討論串中的訊息數量。您也可以在相應的 DevByte 影片中找到這個程式碼範例。
在討論串中新增草稿和郵件
如果您要傳送或遷移的郵件是回覆其他電子郵件,或是對話的一部分,應用程式應將該郵件加入相關討論串。這樣一來,參與對話的 Gmail 使用者就能更輕鬆地掌握訊息脈絡。
您可以將草稿新增至執行建立、更新或傳送草稿訊息的執行緒。您也可以在插入或傳送訊息時,一併新增訊息至討論串。
如要加入討論串,郵件或草稿必須符合下列條件:
- 您在要求中提供的
Message
或 Draft.Message
,必須指定要求的 threadId
。
References
和 In-Reply-To
標頭必須按照 RFC 2822 標準設定。
Subject
標頭必須相符。
請參閱建立草稿或傳送訊息的範例。在這兩種情況下,您只需將與執行緒 ID 配對的 threadId
鍵新增至訊息的中繼資料 (message
物件)。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-29 (世界標準時間)。
[null,null,["上次更新時間: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."]]