高级 Gmail 服务

通过高级 Gmail 服务,您可以在 Apps 脚本中使用 Gmail API。与 Apps 脚本的内置 Gmail 服务非常相似,此 API 允许脚本查找和修改 Gmail 邮箱中的会话、邮件和标签。在大多数情况下,内置服务更易于使用,但这项高级服务提供了一些额外的功能,并且可以访问有关 Gmail 内容的更多详细信息。

参考

如需详细了解此服务,请参阅 Gmail API 的参考文档。与 Apps 脚本中的所有高级服务一样,高级 Gmail 服务使用与公共 API 相同的对象、方法和参数。如需了解详情,请参阅如何确定方法签名

如需报告问题和寻求其他支持,请参阅 Gmail 支持指南

示例代码

以下示例代码使用的是 API 的版本 1

列出标签信息

以下示例演示了如何列出用户的所有标签信息。这包括标签名称、类型、ID 和公开范围设置。

advanced/gmail.gs
/**
 * Lists the user's labels, including name, type,
 * ID and visibility information.
 */
function listLabelInfo() {
  try {
    const response =
      Gmail.Users.Labels.list('me');
    for (let i = 0; i < response.labels.length; i++) {
      const label = response.labels[i];
      console.log(JSON.stringify(label));
    }
  } catch (err) {
    console.log(err);
  }
}

列出收件箱代码段

以下示例演示了如何列出与用户收件箱中每个会话关联的文本片段。请注意使用页面令牌来访问完整的结果列表。

advanced/gmail.gs
/**
 * Lists, for each thread in the user's Inbox, a
 * snippet associated with that thread.
 */
function listInboxSnippets() {
  try {
    let pageToken;
    do {
      const threadList = Gmail.Users.Threads.list('me', {
        q: 'label:inbox',
        pageToken: pageToken
      });
      if (threadList.threads && threadList.threads.length > 0) {
        threadList.threads.forEach(function(thread) {
          console.log('Snippet: %s', thread.snippet);
        });
      }
      pageToken = threadList.nextPageToken;
    } while (pageToken);
  } catch (err) {
    console.log(err);
  }
}

列出近期的历史记录

以下示例演示了如何记录近期活动历史记录。具体来说,此示例会恢复与用户最近发送的消息相关联的历史记录 ID,然后记录自那时起更改的每条消息的消息 ID。无论历史记录中存储了多少个更改事件,每条更改的消息都只记录一次。请注意使用页面令牌来访问完整的结果列表。

advanced/gmail.gs
/**
 * Gets a history record ID associated with the most
 * recently sent message, then logs all the message IDs
 * that have changed since that message was sent.
 */
function logRecentHistory() {
  try {
    // Get the history ID associated with the most recent
    // sent message.
    const sent = Gmail.Users.Threads.list('me', {
      q: 'label:sent',
      maxResults: 1
    });
    if (!sent.threads || !sent.threads[0]) {
      console.log('No sent threads found.');
      return;
    }
    const historyId = sent.threads[0].historyId;

    // Log the ID of each message changed since the most
    // recent message was sent.
    let pageToken;
    const changed = [];
    do {
      const recordList = Gmail.Users.History.list('me', {
        startHistoryId: historyId,
        pageToken: pageToken
      });
      const history = recordList.history;
      if (history && history.length > 0) {
        history.forEach(function(record) {
          record.messages.forEach(function(message) {
            if (changed.indexOf(message.id) === -1) {
              changed.push(message.id);
            }
          });
        });
      }
      pageToken = recordList.nextPageToken;
    } while (pageToken);

    changed.forEach(function(id) {
      console.log('Message Changed: %s', id);
    });
  } catch (err) {
    console.log(err);
  }
}