스레드 관리
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Gmail API는 Thread
리소스를 사용하여 이메일 답장을 원본 메일과 함께 하나의 대화 또는 스레드로 그룹화합니다. 이를 통해 대화의 모든 메시지를 순서대로 가져올 수 있으므로 메시지의 컨텍스트를 파악하거나 검색 결과를 쉽게 개선할 수 있습니다.
메일과 마찬가지로 스레드에도 라벨을 적용할 수 있습니다. 하지만 메시지와 달리 스레드는 생성할 수 없고 삭제만 가능합니다. 하지만 메시지는 대화목록에 삽입할 수 있습니다.
목차
스레드 가져오기
스레드는 대화에서 메시지를 순서대로 가져오는 간단한 방법을 제공합니다.
일련의 스레드를 나열하면 대화별로 메시지를 그룹화하고 추가 컨텍스트를 제공할 수 있습니다. threads.list
메서드를 사용하여 스레드 목록을 가져오거나 threads.get
를 사용하여 특정 스레드를 가져올 수 있습니다. Message
리소스와 동일한 쿼리 매개변수를 사용하여 스레드를 필터링할 수도 있습니다. 스레드의 메시지가 쿼리와 일치하면 해당 스레드가 결과에 반환됩니다.
아래 코드 샘플은 받은편지함에서 가장 대화가 많은 스레드를 표시하는 샘플에서 두 메서드를 모두 사용하는 방법을 보여줍니다. threads.list
메서드는 모든 스레드 ID를 가져오고 threads.get
는 각 스레드의 모든 메시지를 가져옵니다.
답글이 3개 이상인 경우 Subject
줄을 추출하고 비어 있지 않은 줄과 대화목록의 메시지 수를 표시합니다. 이 코드 샘플은 해당 DevByte 동영상에도 소개되어 있습니다.
스레드에 초안 및 메시지 추가
다른 이메일에 대한 응답이거나 대화의 일부인 메시지를 전송하거나 이전하는 경우 애플리케이션은 해당 메시지를 관련 대화목록에 추가해야 합니다. 이렇게 하면 대화에 참여하는 Gmail 사용자가 메시지를 맥락에 맞게 유지하기가 더 쉬워집니다.
초안은 초안 메시지를 만들기, 업데이트 또는 전송하는 과정에서 스레드에 추가할 수 있습니다.
메시지를 삽입하거나 전송할 때 스레드에 메시지를 추가할 수도 있습니다.
메일이나 초안이 스레드에 포함되려면 다음 기준을 충족해야 합니다.
- 요청된
threadId
는 요청과 함께 제공하는 Message
또는 Draft.Message
에 지정해야 합니다.
References
및 In-Reply-To
헤더는 RFC 2822 표준을 준수하여 설정해야 합니다.
Subject
헤더가 일치해야 합니다.
초안 만들기 또는 메일 보내기 예시를 참고하세요. 두 경우 모두 스레드 ID와 페어링된 threadId
키를 메시지의 메타데이터인 message
객체에 추가하면 됩니다.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-08-29(UTC)
[null,null,["최종 업데이트: 2025-08-29(UTC)"],[],[],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."]]