進階 Gmail 服務

您可以使用 Advanced Gmail 服務,在 Apps Script 中使用 Gmail API。與 Apps Script 的內建 Gmail 服務類似,這個 API 可讓指令碼在 Gmail 信箱中尋找及修改討論串、郵件和標籤。在大多數情況下,內建服務較容易使用,但進階服務提供一些額外功能,並可存取 Gmail 內容的詳細資訊。

參考資料

如要進一步瞭解這項服務,請參閱 Gmail API 的參考說明文件。與 Apps Script 中的所有進階服務一樣,進階 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);
  }
}

列出訊息

以下範例說明如何列出 Gmail 使用者的未讀郵件。

advanced/gmail.gs
/**
 * Lists unread messages in the user's inbox using the advanced Gmail service.
 */
function listMessages() {
  // The special value 'me' indicates the authenticated user.
  const userId = 'me';

  // Define optional parameters for the request.
  const options = {
    maxResults: 10, // Limit the number of messages returned.
    q: 'is:unread', // Search for unread messages.
  };

  try {
    // Call the Gmail.Users.Messages.list method.
    const response = Gmail.Users.Messages.list(userId, options);
    const messages = response.messages;
    console.log('Unread Messages:');

    for (const message of messages) {
      console.log(`- Message ID: ${message.id}`);
    }
  } catch (err) {
    // Log any errors to the Apps Script execution log.
    console.log(`Failed with error: ${err.message}`);
  }
}