고급 Gmail 서비스

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