管理會話串

本文說明如何使用 Gmail API 擷取郵件串中的郵件,以及在郵件串中新增郵件。

Gmail API 會使用 threads 資源,將電子郵件回覆與原始郵件整合成單一會話或會話串。這項功能會依序擷取對話中的所有訊息,方便您瞭解訊息的來龍去脈,或縮小搜尋範圍。

messages 資源一樣,執行緒也可以套用標籤。不過,與訊息不同的是,您無法建立執行緒,只能刪除。但可以將訊息插入會話串。

擷取執行緒

討論串可依序擷取對話中的訊息。列出一系列執行緒後,您可以選擇依對話分組訊息,並提供額外背景資訊。您可以使用 threads.list 方法擷取執行緒清單,或使用 threads.get 方法擷取特定執行緒。

下列程式碼範例說明如何在範例中使用 threads.getthreads.list 方法,擷取收件匣中最多人參與的討論串。threads.list 方法會擷取所有執行緒 ID,然後 threads.get 會擷取每個執行緒中的所有訊息。如果訊息有三則以上的回覆,我們會擷取 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 資源將訊息加入執行緒。

如要加入討論串,草稿或郵件必須符合下列條件:

  1. 您必須在要求中提供的 drafts.messagemessages 資源中,指定要求的 threadId

  2. ReferencesIn-Reply-To 標頭必須按照 RFC 2822 標準設定。

  3. Subject 標頭必須相符。

如需如何使用 threadId 的程式碼範例,請參閱「建立草稿」或「傳送訊息」。在這兩種情況下,您都需要在要求的 messages 資源中加入目標 threadId