Google Apps 脚本快速入门

创建向 Gmail API 发出请求的 Google Apps 脚本

快速入门介绍了如何设置和运行调用 Google Workspace API 的应用。本快速入门使用一种简化的身份验证方法,该方法适用于测试环境。对于生产环境,我们建议您先了解身份验证和授权,然后再选择适合您应用的访问凭据

在 Apps 脚本中,Google Workspace 快速入门指南使用高级 Google 服务来调用 Google Workspace API 并处理身份验证和授权流程的一些详细信息。

目标

  • 配置环境。
  • 创建并配置脚本。
  • 运行脚本。

前提条件

  • 已启用 Gmail 的 Google 账号。

  • Google 云端硬盘访问权限

创建脚本

  1. 前往 script.google.com/create,创建一个新脚本。
  2. 将脚本编辑器的内容替换为以下代码:

gmail/quickstart/quickstart.gs
/**
 * Lists all labels in the user's mailbox
 * @see https://developers.google.com/gmail/api/reference/rest/v1/users.labels/list
 */
function listLabels() {
  try {
    // Gmail.Users.Labels.list() API returns the list of all Labels in user's mailbox
    const response = Gmail.Users.Labels.list('me');
    if (!response || response.labels.length === 0) {
      // TODO (developer) - No labels are returned from the response
      console.log('No labels found.');
      return;
    }
    // Print the Labels that are available.
    console.log('Labels:');
    for (const label of response.labels ) {
      console.log('- %s', label.name);
    }
  } catch (err) {
    // TODO (developer) - Handle exception on Labels.list() API
    console.log('Labels.list() API failed with error %s', err.toString());
  }
}

  1. 点击“保存”图标
  2. 点击未命名项目,输入 Quickstart,然后点击重命名

配置脚本

启用 Gmail API

打开 Apps 脚本项目。

  1. 点击编辑器
  2. 服务旁边,点击“添加服务”图标
  3. 选择 Gmail API,然后点击添加

运行示例

在 Apps 脚本编辑器中,点击运行

首次运行该示例时,系统会提示您授权访问:

  1. 点击查看权限
  2. 选择账号。
  3. 点击允许

脚本的执行日志会显示在窗口底部。

后续步骤