emailgoogle-apps-scriptgmailemail-parsing

Get Gmail Messages under the label without Threads using Google Apps Script


I receive order emails daily. Sometimes they are grouped in the same thread, and sometimes they are individual but belongs to the thread. They all go under the same label "InProcess", when I use firstLabel.getThreads() it only gets the emails which belong to the thread. Here is the sample script:

function processEmails() { 

  var firstLabel = GmailApp.getUserLabelByName('FromLabel');
  var secondLabel = GmailApp.getUserLabelByName('ToLabel');
  var threads = firstLabel.getThreads(); 


  if (threads.length > 0) {

    for (var i = threads.length - 1; i >= 0; i--) {
      var thread = threads[i];
      var messages = thread.getMessages(); // Get all messages in the thread

      for (var j = 0; j < messages.length; j++) {
        var message = messages[j]; // Process each message in the thread
        var plainBody = message.getPlainBody();
        console.log(plainBody);

        //do the processing

       
      // Label the thread as processed and remove the original label
      thread.addLabel(secondLabel).refresh(); // Mark thread as processed
      thread.removeLabel(firstLabel).refresh(); // Remove the original label
    }
   }
  }
}

So, it either gets all the messages of the thread or no message if it is separated from the thread. For example in the below screenshot, script says that there is only one thread that has multiple messages, leaving the other 2 emails unprocessed (which are ungrouped/splitted from certain threads):

Emails

I want to just get these 3 messages/emails without considering the thread. Is there any query something like GmailApp.search('label:'+ ?) that we can use to get only messages. Any guidance would be much appreciated.


Solution

  • I found a workaround to this from the following source, the script that gets only the messages and not threads is:

    function listMessages () {
      // Only return messages matching the specified query.
      var msgs = Gmail.Users.Messages.list('me', {'q':'label:InProcess'}).messages;
    
      msgs.forEach(function (e){
       var message = GmailApp.getMessageById(e.id); // Fetch message by its ID
       var plainBody = message.getPlainBody();
      });
    
    }