Home > Enterprise >  For Loop using Google Scripts to read an email
For Loop using Google Scripts to read an email

Time:08-10

We are trying to create a script that reads through certain emails based on how they are labeled and write certain content to a spreadsheet. We are able to write only one email worth of data to the spreadsheet before our loop states .getPlainBody() is undefined. Below is our code and the exact error we are getting

TypeError: Cannot read property 'getPlainBody' of undefined
myFunction  @ Code.gs:12

Any help would be greatly appreciated!

function myFunction() {
  var ss = SpreadsheetApp.openById("105dNWvYNTPzqw1YHHclu00vKLclyEi9UjQBoX0_JTYM");
  var sheet = ss.getSheetByName("Daily Log Data");
    
  var label =GmailApp.getUserLabelByName("Test");
  var threads = label.getThreads();
  Logger.log(threads);

  for(var i = 0; i < threads.length; i  ) {
    var mess = threads[i].getMessages();
    var pmsg = mess[i].getPlainBody();

    Logger.log(mess);
  
    // Mutual Aid
    if (pmsg.includes("MutualAid: ")>0) {
      var endMut = pmsg.substring(mess.indexOf("MutualAid: ") 11,pmsg.length);
      var Mut = endMut.substring(0,endMut.indexOf("\n"));
      sheet.appendRow([Mut]);
    }
  }
}

CodePudding user response:

Try it this way:

function myFunction() {
  var ss = SpreadsheetApp.openById("105dNWvYNTPzqw1YHHclu00vKLclyEi9UjQBoX0_JTYM");
  var sh = ss.getSheetByName("Daily Log Data");
  var lbl = GmailApp.getUserLabelByName("Test");
  var threads = lbl.getThreads();
  for (var i = 0; i < threads.length; i  ) {
    var mess = threads[i].getMessages();
    for (var j = 0; j < mess.length; j  ) {
      var pmsg = mess[j].getPlainBody();
      if (pmsg.includes("MutualAid: ") > 0) {
        var endMut = pmsg.substring(mess.indexOf("MutualAid: ")   11, pmsg.length);
        var Mut = endMut.substring(0, endMut.indexOf("\n"));
        sh.appendRow([Mut]);
      }
    }
  }
}
  • Related