Zaawansowana usługa Gmail

Zaawansowana usługa Gmail umożliwia korzystanie z interfejsu Gmail API w Apps Script. Podobnie jak wbudowana usługa Gmail w Apps Script ten interfejs API umożliwia skryptom znajdowanie i modyfikowanie wątków, wiadomości i etykiet w skrzynce pocztowej Gmail. W większości przypadków usługa wbudowana jest łatwiejsza w użyciu, ale ta usługa zaawansowana zapewnia kilka dodatkowych funkcji i dostęp do bardziej szczegółowych informacji o treściach w Gmailu.

Dokumentacja

Szczegółowe informacje o tej usłudze znajdziesz w dokumentacji referencyjnej interfejsu Gmail API. Podobnie jak wszystkie usługi zaawansowane w Apps Script, zaawansowana usługa Gmaila używa tych samych obiektów, metod i parametrów co publiczny interfejs API. Więcej informacji znajdziesz w artykule Jak określane są podpisy metod.

Aby zgłosić problemy i uzyskać inną pomoc, zapoznaj się z przewodnikiem pomocy Gmaila.

Przykładowy kod

Poniższy przykładowy kod korzysta z wersji 1 interfejsu API.

Wyświetlanie informacji o etykiecie

Poniższy przykład pokazuje, jak wyświetlić wszystkie informacje o etykietach użytkownika. Obejmuje to nazwę, typ, identyfikator i ustawienia widoczności etykiety.

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);
  }
}

Wyświetlanie listy fragmentów skrzynki odbiorczej

Przykład poniżej pokazuje, jak wyświetlić listę fragmentów tekstu powiązanych z każdym wątkiem w skrzynce odbiorczej użytkownika. Zwróć uwagę na użycie tokenów strony, aby uzyskać dostęp do pełnej listy wyników.

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);
  }
}

Wyświetlanie najnowszej historii

Poniższy przykład pokazuje, jak rejestrować historię ostatniej aktywności. W tym przykładzie odzyskiwany jest identyfikator rekordu historii powiązany z ostatnio wysłaną wiadomością użytkownika, a następnie rejestrowane są identyfikatory wszystkich wiadomości, które uległy zmianie od tego czasu. Każda zmieniona wiadomość jest rejestrowana tylko raz, niezależnie od tego, ile zdarzeń zmiany znajduje się w historii. Zwróć uwagę na użycie tokenów strony, aby uzyskać dostęp do pełnej listy wyników.

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);
  }
}

Wyświetlanie listy wiadomości

Poniższy przykład pokazuje, jak wyświetlić listę nieprzeczytanych wiadomości użytkownika Gmaila.

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}`);
  }
}