管理话题

本文档介绍了如何使用 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. 所请求的 threadId 必须在您随请求提供的 drafts.messagemessages 资源中指定。

  2. ReferencesIn-Reply-To 标头必须按照 RFC 2822 标准进行设置。

  3. Subject 标头必须一致。

如需查看有关如何使用 threadId 的代码示例,请参阅创建草稿发送消息。在这两种情况下,您都需要在请求的 messages 资源中添加目标 threadId