How to read all mails from inbox in google script?

坚强是说给别人听的谎言 提交于 2020-01-11 12:33:29

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/55722600/how-to-read-all-mails-from-inbox-in-google-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!