Google Script – get data from Gmail into Sheet

Tags: , , , ,



I have been looking around here on SO and on Google, but I cannot find anything that is working.

So when I am running my code below, I am getting the result on the image.

I want to extract data from the newest/most recent thread in mails that have a specific label.

However, in my Gmail, I only have the 3 mails under "Action"-label that I have highlighted in bold.
The other mails have been deleted, hence, they are in trash, but do still have the “Action” label.

I want to only show the mails that I have "Action"-label on – meaning that I only want the newest thread time/date, subject line as well as the ID, so I can create a link to that mail.

Google Sheet data example

function myFunction() {

  var ss = SpreadsheetApp.getActiveSheet();

  var query = "label:action -label:trash -label:action-done -from:me";

  var threads = GmailApp.search(query);

    for (var i = 0; i < threads.length; i++)
    {
      var messages = threads[i].getMessages();

      for (var j = 0; j < messages.length; j++)
      {
        var mId = messages[j].getId()
        var from = messages[j].getFrom();
        var cc = messages[j].getCc();
        var time = messages[j].getDate()
        var sub = messages[j].getSubject();

        ss.appendRow([from, cc, time, sub, 'https://mail.google.com/mail/u/0/#inbox/'+mId])
      }
    }
  }
}

Answer

So I managed to solve it, by finding the max index in the array.
I have commented the code, so it can help others. Thanks, all.

function myFunction() {
  // Use sheet
  var ss = SpreadsheetApp.getActiveSheet();
  // Gmail query
  var query = "label:support -label:trash -label:support-done -from:me";
  // Search in Gmail, bind to array
  var threads = GmailApp.search(query);
  // Loop through query results
  for (var i = 0; i < threads.length; i++)
  {
    // Get messages in thread, add to array
    var messages = threads[i].getMessages();

    // Used to find max index in array
    var max = messages[0];
    var maxIndex = 0;

    // Loop through array to find maxIndexD = most recent mail
    for (var j = 0; j < messages.length; j++) {
      if (messages[j] > max) {
        maxIndex = j;
        max = messages[j];
      }
    } 
    // Find data
    var mId = messages[maxIndex].getId() // ID used to create mail link
    var from = messages[maxIndex].getFrom();
    var cc = messages[maxIndex].getCc();
    var time = threads[i].getLastMessageDate()
    var sub = messages[maxIndex].getSubject();
    // Write data to sheet
    ss.appendRow([from, cc, time, sub, 'https://mail.google.com/mail/u/0/#inbox/'+mId])
  }
}


Source: stackoverflow