Home > database >  google scripts throwing not a function error for getMessages()
google scripts throwing not a function error for getMessages()

Time:06-14

I am trying to create a script for an autoreply function. I am currently trying to grab each of the emails assigned to a specific label and grab specific details off of each email, however I am receiving an error stating TypeError: threads.getMessages is not a function, even though I have triple checked that this is, indeed, a function of the GMAIL scripting. Have I done something wrong here in this code that may be causing this error?

  var labelName = "auto-reply-incoming";
  var receivedCount = 0;

// extract emails from label in Gmail
function extractEmails() {
  // get all email threads that match label
  var receivedSearchQuery = "label:" labelName " -is:sent";
  var threads = GmailApp.search(receivedSearchQuery, 0, 500);
  
  for (var i=0; i<threads.length; i  ) {
    //count received emails in label
    receivedCount = receivedCount   threads[i].getMessageCount();
    //get body of each email
    var message = threads.getMessages()[i].getBody();
    //get recipient of each email
    var recipient = threads.getMessages()[i].getTo();
  }
  Logger.log(receivedCount);
  Logger.log(recipient);
}

CodePudding user response:

The problem occurs because the code is using the threads iterator that might be bigger than the number of messages on certain threads, more specifically, the problem is in the following lines:

    //get body of each email
    var message = threads.getMessages()[i].getBody();
    //get recipient of each email
    var recipient = threads.getMessages()[i].getTo();

Here is a quick fix (replace the above, by the following)

    var messages = threads[i].getMessages();
    for( j = 0; j < messages.length; j  ){
      //get body of each email
      var message = messages[j].getBody();
      //get recipient of each email
      var recipient = messages[j].getTo();
    }

Note: Logger.log(recipient) will log the recipient of the last message of the last thread.

CodePudding user response:

Try this:

function extractEmails() {
  var labelName = "auto-reply-incoming";
  var receivedCount = 0;
  var receivedSearchQuery = "label:"   labelName   " -is:sent";
  var ts = GmailApp.search(receivedSearchQuery, 0, 500);
  var a = [];
  ts.forEach((t, i) => {
    let ms = t.getMessages();
    ms.forEach((m, j) => {
      let msg = m.getBody();
      let rec = m.getTo();
      a.push({ threadindex: j, messageindex: i, message: msg, recipient: rec })
    });
  });
  Logger.log(JSON.stringify(a));
}
  • Related