0
votes

I am a big amateur in Google App Script.

Rescued this script that works for me but not correctly. Now only read and phsarse info for the first message of the thread not all the messages.

I need to read,check, and pharse all messages of a label, not only the first of the thread. I need that the script read and pharse all the individual messages located on a tag. Then marks all as read.

Someone could help me and change the code to do this? I review Google APP Script manual and I've tried different things but I can't get it to work.

Thanks!

  //var threads = GmailApp.getInboxThreads();
  // Have to get data separate to avoid google app script limit!
  var start = 0;
  var threads = GmailApp.search("newer_than:1d AND is:unread AND label:eur OR label:desc",0,100); 
  var sheet = SpreadsheetApp.getActiveSheet();
  var result = [];

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

    var content = messages[0].getPlainBody();
    messages[0].markRead();
    // implement your own parsing rule inside
    if (content) {
      var tmp;
      tmp = content.match(/\b([A-B\d][A-B\d]{4})\b/);
      var cod = (tmp && tmp[1]) ? tmp[1].trim() : 'Error';

      tmp = content.match(/\b(\d+[R])/);
      var prom = (tmp && tmp[1]) ? tmp[1].trim() : 'Error';

      tmp = content.match(/\b(\d{2}\.\d{2}\)\b/);
      var exp = (tmp && tmp[1]) ? tmp[1].trim() : 'Error';

      sheet.appendRow([cod, prom, exp]);

      Utilities.sleep(500);
    }


  }
}; ```
2

2 Answers

1
votes

In order to mark messages as read, you have to iterate messages of each thread.

You are only getting the first message of the thread, so you have to replace

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

  var content = messages[0].getPlainBody();
  messages[0].markRead();

  .....

to something like this:

function readMails (){

  var threads = GmailApp.search("newer_than:1d AND is:unread AND label:eur OR label:desc",0,100);

  //Iterate threads
  for (var i=0; i < threads.length; i++){

    var messages = threads[i].getMessages();

    //Iterate messages of each thread
    for (var k=0; k < messages.length; k++){
      var content = messages[k].getPlainBody();
      messages[k].markRead();

      .....
    }
  }
}
0
votes

Since you have a list of threads already, you can use the markThreadsRead method to mark them all read in one go.

var threads = GmailApp.search("newer_than:1d AND is:unread AND label:eur OR label:desc",0,100); 
GmailApp.markThreadsRead(threads);

Alternatively, you can process individual messages in the thread as below:

var messages = threads[i].getMessages();
messages.forEach(function(message) {
  message.markRead();
  // processs the message here and save to sheets
})