How to read all mails from inbox in google script?
Asked Answered
C

1

6

the script below returns only records of 500 mails. the google developer help states clearly "Where the thread size is unknown, and potentially very large, please use the 'paged' call, and specify ranges of the threads to retrieve in each call." what is paged call ? how to do it ? I have even tried GmailApp.getInboxThreads(start,end) it displays error if the parameters are >500. how to read all the 22000 mails in my inbox ?

//google script
function spreadsheetSaver() 
{
   var emailSheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
   emailSheet.clear();
    var thread = GmailApp.getInboxThreads();
    var row = 1;
    for(var i=0;i<thread.length;i++)
    {
      var mail = thread[i].getMessages();
      for(var msg in mail)
      {
        var message = mail[msg];
        if (message && message.isInInbox())
        {
          var txt = message.getPlainBody();
          emailSheet.getRange(row++,1).setValue(txt);
        }
      }
    }
};

the expected output must save all the 22000 mails in a spreadsheet

Clinician answered 17/4, 2019 at 7:54 Comment(2)
Tell us about the errors.Endamoeba
When you read a lot of emails, also please be careful the quotas of "Email read/write". You can see it at here.Overabound
B
10

You must retrieve threads in batches of 500 and update thread indices after each loop iteration. You stop the loop when the length of the retrieved threads array is no longer equal to the maximum number of threads - in other words, there are fewer than 500 threads left to process. Here's the simple code

 var startIndex = 0;
 var maxThreads = 500;

 do {

    threads = GmailApp.getInboxThreads(startIndex, maxThreads);     

    for(var i=0; i < threads.length; i++) {

      //Do something

    }

    //Increment startIndex by 500 after having processed 500 threads

    startIndex += maxThreads;

  } while (threads.length == maxThreads);

Unfortunately, you'll run into other issues like execution time quotas. There's no way to process all 22000 messages in a single call without exceeding the quota. You must monitor execution time and stop the script when the script runtime gets close to the one set by the quota (6 minutes runtime for personal accounts) and re-schedule the script to run again using ScriptApp.newTrigger(functionName). You must also store the value of 'startIndex' between calls - consider using PropertiesService.

Buddy answered 17/4, 2019 at 8:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.