Search code examples
google-apps-scriptgmail

Import email Subject into a Google spreadsheet using sample code


I'm trying to make code work that I found on a Stackoverflow post

@Serge insas posted the following code

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)
    }

So in my attempt to make this code work I created a gmail 'label' called 'Facebook'.

  • I moved an email into that 'Facebook' label.
  • I then created a spreadsheet.
  • I went into script editor for that spreadsheet
  • I created a spreadsheet script
  • I added the code posted above
  • I ran the functions and authorized them
  • I ran the GetMessagesWithLabel function again and I get the following error.

TypeError: Cannot read property "length" from undefined. (line 53, file "Code")

Line 53 is sh.getRange(ss.getLastRow()+1,1,destArray.length,destArray[0].length).setValues(destArray)

I am hoping someone can help me make this example work.

Regards,

Chris


Solution

  • This line:

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

    Has an error.

    This method:

    getThreads(1,10)
    

    should have a zero parameter rather than a 1.

    getThreads(0,10)
    

    The index starts with zero, not one. You only have one email in the new "Facebook" label. A starting index of 1, starts to retrieve the second email, and then goes up to ten.