Layanan Gmail Lanjutan

Layanan Gmail Lanjutan memungkinkan Anda menggunakan Gmail API di Apps Script. Seperti layanan Gmail bawaan Apps Script, API ini memungkinkan skrip menemukan dan mengubah rangkaian pesan, pesan, dan label di kotak surat Gmail. Dalam sebagian besar kasus, layanan bawaan lebih mudah digunakan, tetapi layanan lanjutan ini menyediakan beberapa fitur tambahan dan akses ke informasi yang lebih mendetail tentang konten Gmail.

Referensi

Untuk mengetahui informasi mendetail tentang layanan ini, lihat dokumentasi referensi untuk Gmail API. Seperti semua layanan lanjutan di Apps Script, layanan Gmail lanjutan menggunakan objek, metode, dan parameter yang sama dengan API publik. Untuk mengetahui informasi selengkapnya, lihat Cara menentukan tanda tangan metode.

Untuk melaporkan masalah dan menemukan dukungan lainnya, lihat panduan dukungan Gmail.

Kode contoh

Contoh kode di bawah menggunakan API versi 1.

Mencantumkan informasi label

Contoh berikut menunjukkan cara mencantumkan semua informasi label pengguna. Hal ini mencakup nama label, jenis, ID, dan setelan visibilitas.

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

Mencantumkan cuplikan kotak masuk

Contoh berikut menunjukkan cara mencantumkan cuplikan teks yang terkait dengan setiap rangkaian pesan di Kotak Masuk pengguna. Perhatikan penggunaan token halaman untuk mengakses daftar lengkap hasil.

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

Mencantumkan histori terbaru

Contoh berikut menunjukkan cara mencatat histori aktivitas terbaru. Secara khusus, contoh ini memulihkan ID rekaman histori yang terkait dengan pesan yang terakhir dikirim pengguna, lalu mencatat ID pesan dari setiap pesan yang telah berubah sejak saat itu. Setiap pesan yang diubah hanya dicatat sekali, berapa pun jumlah peristiwa perubahan dalam catatan histori. Perhatikan penggunaan token halaman untuk mengakses daftar lengkap hasil.

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

Mencantumkan pesan

Contoh berikut menunjukkan cara mencantumkan pesan yang belum dibaca pengguna 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}`);
  }
}