Google Script – Pull Gmail Addresses into Spreadsheet

gmailgoogle sheetsgoogle-apps-script

This Google Script goes through and finds the emails in my Gmail which are in a label called "LabelToGet" and sends me a link to the spreadsheet created with these emails:

function createAndSendDocument() {
  // Create a new document with the title 'Email Contacts'
  var doc = SpreadsheetApp.create('My Contacts');

  var sh = doc.insertSheet('Emails', 0);

   // get all messages
   var eMails = GmailApp.getMessagesForThreads(
     GmailApp.search("label:LabelToGet"))
     .reduce(function(a, b) {return a.concat(b);})
     .map(function(eMails) {
        return eMails.getFrom() 
      });

   // sort and filter for unique entries  
   var aEmails = eMails.sort().filter(function(el,j,a){if(j==a.indexOf(el))return 1;return 0});  

   // create 2D-array
   var aUnique = new Array();  
   for(var k in aEmails) {
     aUnique.push([aEmails[k]]);
   }

   // add data to sheet
   sh.getRange(1, 1, aUnique.length, 1).setValues(aUnique);

  // Get the URL of the document
  var url = doc.getUrl();

  // Get the email address of the active user - that's you
  var emailAddress = Session.getActiveUser().getEmail();

  // Send yourself an email with a link to the document
  GmailApp.sendEmail(emailAddress,
                     'Heres the link to it',
                     'click here: ' + url);
}

It works well, but I have thousands of emails in this label, and the script only seems to be running through the most recent 500.

Does anybody know what might be causing this not to look through ALL emails in that label or what I can do to make that happen?

Best Answer

Gmail.search would only return the first few hundred emails and if you would like to retrieve the later message, you may have to specify the offset parameter.

I previously wrote a Google Script for extracting email addresses from a Gmail folder and it does work with the previous messages as well.