2

I am trying to use the code below that i got from this link:

Import emails that fit criteria to Google Spreadsheet using apps script

and it is giving me the error

TypeError: Cannot read property "length" from undefined.

Can someone help?

   function getMessagesWithLabel() {
     var destArray = new Array();
      var threads = GmailApp.getUserLabelByName('Facebook').getThreads(1,10);

      for(var n in threads){
            var msg = threads[n].getMessages();
            var destArrayRow = new Array();
            destArrayRow.push('thread has '+threads[n].getMessageCount()+' messages');
              for(var m in msg){
                         destArrayRow.push(msg[m].getSubject());
               }
      destArray.push(destArrayRow);           
            }
    Logger.log(destArray);
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sh = ss.getActiveSheet();
    if(ss.getLastRow()==0){sh.getRange(1,1).setValue('getMessagesWithLabel() RESULTS')};
    sh.getRange(ss.getLastRow()+1,1,destArray.length,destArray[0].length).setValues(destArray)
    }
4
  • 2
    If threads is empty (because GmailApp.getUserLabelByName has an empty result, then destArray will be empty, and destArray[0] will be non-existant (undefined). You'll want to check whether threads is not empty before proceeding. Commented Jun 9, 2015 at 3:35
  • Other people have used this code by only changing the label name. What am i doing wrong? Commented Jun 9, 2015 at 3:40
  • getUserLabelByName('Facebook'). do your Gmail labels include Facebook? Commented Jun 9, 2015 at 3:54
  • I found out the problem var threads = GmailApp.getUserLabelByName('Facebook').getThreads(1,10) should be var threads = GmailApp.getUserLabelByName('Facebook').getThreads(0,10) Commented Jun 9, 2015 at 3:56

1 Answer 1

1

The problem is if there are no elements in GmailApp.getUserLabelByName('Facebook').getThreads(1,10); then threads will be null and the loop for(var n in threads) will not work

this means that you need to type

var threads = GmailApp.getUserLabelByName('Facebook').getThreads(1,10);

if (threads != null) {
  for(var n in threads) {
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.