高级 Gmail 服务

借助高级 Gmail 服务,您可以在 Apps 脚本。与 Apps 脚本的内置 Gmail 服务非常相似, 此 API 允许脚本查找和修改 Gmail 邮箱。在大多数情况下,内置服务更易于使用, 高级服务提供了一些额外功能, 有关 Gmail 内容的信息。

参考

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

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

示例代码

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

列出标签信息

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

高级/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);
  }
}

列出收件箱摘要

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

高级/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);
  }
}

列出近期历史记录

以下示例演示了如何记录近期活动历史记录。 具体而言,此示例恢复了与 用户最近发送的邮件,然后记录每 那之后更改的留言。系统只会记录更改的每条消息 无论历史记录中有多少更改事件,都会触发一次。请注意 使用页面令牌访问完整的结果列表。

高级/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);
  }
}