Google Apps Script 快速入門

建立 Google Apps Script,向 Gmail API 提出要求。

快速入門指南會說明如何設定及執行呼叫 Google Workspace API 的應用程式。本快速入門導覽課程會使用簡化的驗證方法,適用於測試環境。在正式環境中,建議您先瞭解驗證和授權,再選擇適合應用程式的存取憑證

在 Apps Script 中,Google Workspace 快速入門導覽會使用進階 Google 服務呼叫 Google Workspace API,並處理驗證和授權流程的部分詳細資料。

目標

  • 設定環境。
  • 建立及設定指令碼。
  • 執行指令碼。

必要條件

  • 已啟用 Gmail 的 Google 帳戶。

  • Google 雲端硬碟存取權

建立指令碼

  1. 前往 script.google.com/create,在 Apps Script 編輯器中建立新指令碼。
  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 Script 專案。

  1. 按一下「編輯器」圖示
  2. 按一下「服務」旁的「新增服務」圖示
  3. 選取「Gmail API」,然後按一下「新增」

執行範例

在 Apps Script 編輯器中,按一下「執行」

首次執行範例時,系統會提示您授權存取權:

  1. 按一下「查看權限」
  2. 選擇所需帳戶。
  3. 按一下「允許」

視窗底部會顯示指令碼的執行記錄。

後續步驟