שירות Gmail מתקדם

שירות Gmail המתקדם מאפשר לכם להשתמש ב-Gmail API ב-Apps Script. בדומה לשירות Gmail המובנה ב-Apps Script,‏ ה-API הזה מאפשר לסקריפטים למצוא ולשנות שרשורים, הודעות ותוויות בתיבת דואר ב-Gmail. ברוב המקרים, קל יותר להשתמש בשירות המובנה, אבל השירות המתקדם הזה מספק כמה תכונות נוספות וגישה למידע מפורט יותר על התוכן ב-Gmail.

חומרי עזר

מידע מפורט על השירות הזה מופיע במאמרי העזרה של Gmail API. בדומה לכל השירותים המתקדמים ב-Apps Script, שירות Gmail המתקדם משתמש באותם אובייקטים, שיטות ופרמטרים כמו ממשק ה-API הציבורי. מידע נוסף זמין במאמר איך נקבעות חתימות של שיטות.

כדי לדווח על בעיות ולמצוא תמיכה נוספת, אפשר לעיין במדריך התמיכה של Gmail.

קוד לדוגמה

בדוגמת הקוד שבהמשך נעשה שימוש בגרסה 1 של ה-API.

הצגת פרטי התווית

בדוגמה הבאה מוצגות כל התוויות של המשתמש. הפרטים האלה כוללים את שם התווית, הסוג, המזהה והגדרות החשיפה.

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

הצגת ההיסטוריה מהתקופה האחרונה

בדוגמה הבאה מוסבר איך לתעד את היסטוריית הפעילות האחרונה. בפרט, בדוגמה הזו מתבצע שחזור של מזהה רשומת ההיסטוריה שמשויך להודעה האחרונה שהמשתמש שלח, ואז מתבצע רישום ביומן של מזהי ההודעות של כל הודעה שהשתנתה מאז. כל הודעה שמשתנה מתועדת רק פעם אחת, לא משנה כמה אירועי שינוי יש ברשומות ההיסטוריה. שימו לב לשימוש באסימוני דפים כדי לגשת לרשימת התוצאות המלאה.

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