Jagrat
Jagrat

Reputation: 15

Google Script: How do I get all messages from multiple threads into an array?

My goal is to get all messages with a particular label into an array.

Currently I'm using Gmailapp.search(), which successfully gives me an array of Gmail threads with the label I've specified. Where I'm stuck is - extracting all the messages of the threads into an array. As you can see in the code below, I'm trying to use the getMessagesForThreads() function, but with the code I have below, the number of threads and number of total messages is the same, which can't be right.

function getRelevantMessages() 
{

var queried_Email_Threads = GmailApp.search ("label:expense tracking/Credit Card");
console.log('Number of threads queried:'+ queried_Email_Threads.length)

var messages = GmailApp.getMessagesForThreads(queried_Email_Threads)
console.log('Total number of messages: ' + messages.length)
}

Upvotes: 0

Views: 1104

Answers (1)

Tanaike
Tanaike

Reputation: 201553

When I saw the official document of the method of getMessagesForThreads, the sample script is as follows.

// Log the subject lines of all messages in the first two threads of your inbox
var thread = GmailApp.getInboxThreads(0, 2);
var messages = GmailApp.getMessagesForThreads(thread);
for (var i = 0 ; i < messages.length; i++) {
  for (var j = 0; j < messages[i].length; j++) {
    Logger.log("subject: " + messages[i][j].getSubject());
  }
}

When this sample script is reflected to your script, it becomes as follows.

Modified script:

function getRelevantMessages() {
  var queried_Email_Threads = GmailApp.search("label:expense tracking/Credit Card");
  console.log('Number of threads queried:' + queried_Email_Threads.length)

  var messages = GmailApp.getMessagesForThreads(queried_Email_Threads)
  console.log('Total number of messages: ' + messages.length)

  // I added below script.
  var res = [];
  for (var i = 0; i < messages.length; i++) {
    for (var j = 0; j < messages[i].length; j++) {
      res.push(messages[i][j]);
    }
  }
  console.log(res.length)
}
  • From the official document,

    GmailMessage[][] (from getMessagesForThreads) - an array of arrays of messages, where each item in the outer array corresponds to a thread and the inner array contains the messages in that thread

References:

Upvotes: 1

Related Questions