Advertisement
marikamitsos

STA-65036762 mail2Sheets script

Nov 27th, 2020 (edited)
643
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // EXECUTION is running forever:  https://i.stack.imgur.com/yZjMw.png
  2. // Execution time (1.749 s) is without the "refreshThreads" command
  3. // FROM: https://stackoverflow.com/questions/65036762/script-to-search-for-multiple-unread-labels-in-gmail-threads-at-once?noredirect=1#comment114980378_65036762
  4. // As from: https://stackoverflow.com/questions/63907655/record-incoming-gmail-messages-in-google-sheets
  5. // AND as from: https://stackoverflow.com/questions/63990923/data-is-not-written-to-google-spreadsheet
  6.  
  7. function mail2Sheets() {
  8.   var ss = SpreadsheetApp.getActive();
  9.   var sheet = ss.getSheetByName('newRec'); //gets the right sheet
  10.   var freshLabel = GmailApp.getUserLabelByName("00-fresh"); // ++++ will add this label in the end
  11.   const query = "label:unread (label:00-atest OR label:00-btest)";
  12.   var foundThreads = GmailApp.search(query);
  13.   var newReceipts = [];
  14.   for (var i = 0; i < foundThreads.length; i++) {
  15.     var messages = foundThreads[i].getMessages();
  16.     for (var m = 0; m < messages.length; m++) {
  17.       var from = messages[m].getFrom(); //from field
  18.       var to = messages[m].getTo(); //to field
  19.       var time = messages[m].getDate(); //date field
  20.       var subject = messages[m].getSubject(); //subject field
  21.       var body = messages[m].getPlainBody(); //body field
  22.       var mId = messages[m].getId(); //id field to create the link later
  23.       newReceipts.push([from,to,time,subject,body,'https://mail.google.com/mail/u/0/#inbox/'+mId]);
  24.     }
  25.   }
  26.   if(!foundThreads.length) return; //  if there are no unread ones, do nothing.
  27.   sheet.getRange(SpreadsheetApp.getActiveSheet().getLastRow()+1,2,newReceipts.length,newReceipts[0].length).setValues(newReceipts); //writes to the spreadsheet
  28.   GmailApp.markThreadsRead(foundThreads); // marks as read
  29.   freshLabel.addToThreads(foundThreads); // ++++ add label "fresh" to found threads
  30.   GmailApp.refreshThreads(foundThreads); // PROBLEM HERE
  31.   sheet.sort(4,false);
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement