스레드 관리

이 문서에서는 Gmail API를 사용하여 대화목록 메시지를 가져오고 대화목록에 메시지를 추가하는 방법을 설명합니다.

Gmail API는 threads 리소스를 사용하여 이메일 답장을 원본 메시지와 함께 하나의 대화 또는 대화목록으로 그룹화합니다. 이렇게 하면 대화의 모든 메시지를 순서대로 가져올 수 있으므로 메시지의 컨텍스트를 파악하거나 검색 결과를 구체화하는 것이 더 쉬워집니다.

messages 리소스와 마찬가지로 대화목록에도 라벨을 적용할 수 있습니다. 그러나 메시지와 달리 대화목록은 만들 수 없고 삭제만 할 수 있습니다. 하지만 메시지는 대화목록에 삽입할 수 있습니다.

대화목록 가져오기

대화목록은 대화의 메시지를 순서대로 가져오는 방법을 제공합니다. 대화목록 집합을 나열하면 대화별로 메시지를 그룹화하고 추가 컨텍스트를 제공할 수 있습니다. threads.list 메서드를 사용하여 대화목록 목록을 가져오거나 threads.get 메서드를 사용하여 특정 대화목록을 가져올 수 있습니다.

다음 코드 샘플은 받은편지함에서 가장 대화가 많은 대화목록을 가져오는 샘플에서 threads.getthreads.list 메서드를 사용하는 방법을 보여줍니다. threads.list 메서드는 모든 대화목록 ID를 가져온 다음 threads.get은 각 대화목록의 모든 메시지를 가져옵니다. 답장이 3개 이상인 메시지의 경우 Subject 행을 추출하고 비어 있지 않은 행과 대화목록의 메시지 수를 표시합니다.

Python

gmail/snippet/thread/threads.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def show_chatty_threads():
  """Display threads with long conversations(>= 3 messages)
  Return: None

  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """
  creds, _ = google.auth.default()

  try:
    # create gmail api client
    service = build("gmail", "v1", credentials=creds)

    # pylint: disable=maybe-no-member
    # pylint: disable:R1710
    threads = (
        service.users().threads().list(userId="me").execute().get("threads", [])
    )
    for thread in threads:
      tdata = (
          service.users().threads().get(userId="me", id=thread["id"]).execute()
      )
      nmsgs = len(tdata["messages"])

      # skip if <3 msgs in thread
      if nmsgs > 2:
        msg = tdata["messages"][0]["payload"]
        subject = ""
        for header in msg["headers"]:
          if header["name"] == "Subject":
            subject = header["value"]
            break
        if subject:  # skip if no Subject line
          print(f"- {subject}, {nmsgs}")
    return threads

  except HttpError as error:
    print(f"An error occurred: {error}")


if __name__ == "__main__":
  show_chatty_threads()

`messages` 리소스에 사용되는 것과 동일한 쿼리 매개변수를 사용하여 대화목록을 필터링할 수도 있습니다. 대화목록의 메시지가 쿼리와 일치하면 대화목록이 결과로 반환됩니다.

대화목록에 초안 및 메시지 추가

다른 이메일에 대한 답장 또는 대화의 일부인 메시지를 보내거나 이전하는 경우 애플리케이션은 해당 메시지를 관련 대화목록에 추가해야 합니다. 이렇게 하면 대화에 참여하는 Gmail 사용자가 메시지를 컨텍스트에 맞게 유지할 수 있습니다.

`drafts` 리소스를 사용하여 메시지를 만들거나, 업데이트하거나 또는 보내는 과정에서 초안을 대화목록에 추가할 수 있습니다.

`messages` 리소스를 사용하여 메시지를 삽입하거나 보내는 과정에서 대화목록에 메시지를 추가할 수도 있습니다.messages

대화목록의 일부가 되려면 초안 또는 메시지가 다음 기준을 충족해야 합니다.

  1. 요청된 threadId 은 요청과 함께 제공하는 drafts.message 또는 messages 리소스의 일부로 지정해야 합니다.

  2. ReferencesIn-Reply-To 헤더는 RFC 2822 표준을 준수하여 설정해야 합니다.

  3. Subject 헤더가 일치해야 합니다.

threadId 사용 방법에 관한 코드 샘플은 초안 또는 메시지 보내기를 참고하세요. 두 경우 모두 요청의 messages 리소스 내에 대상 threadId를 포함해야 합니다.