進階 Gmail 服務

進階 Gmail 服務可讓您在 Apps Script 中使用 Gmail API。與 Apps Script 的內建 Gmail 服務類似,這個 API 可讓指令碼尋找及修改 Gmail 信箱中的執行緒、郵件和標籤。在大多數情況下,內建服務較容易使用,但這項進階服務提供幾項額外功能,以及讓使用者取得更詳細的 Gmail 內容相關資訊。

參考資料

如要進一步瞭解這項服務,請參閱 Gmail API 的參考說明文件。如同 Apps Script 的所有進階服務,進階 Gmail 服務會使用與公用 API 相同的物件、方法和參數。詳情請參閱「如何判定方法簽章」一文。

如要回報問題及尋求其他支援,請參閱 Gmail 支援指南

程式碼範例

下方程式碼範例使用第 1 版的 API。

列出標籤資訊

以下範例說明如何列出所有使用者的標籤資訊。包括標籤名稱、類型、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);
  }
}