如何从Google脚本中的收件箱中读取所有邮件? [英] How to read all mails from inbox in google script?

查看:234
本文介绍了如何从Google脚本中的收件箱中读取所有邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的脚本仅返回500个邮件的记录. google开发人员帮助明确指出:如果线程大小未知且可能很大,请使用'paged'调用,并在每次调用中指定要检索的线程范围." 什么是分页通话?怎么做 ? 我什至尝试过GmailApp.getInboxThreads(start,end),如果参数> 500,它会显示错误. 如何阅读我的收件箱中的所有22000邮件?

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

预期输出必须将所有22000封邮件保存在电子表格中

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

推荐答案

每次循环迭代后,您必须分批检索500个线程并更新线程索引.当检索到的线程数组的长度不再等于最大线程数时,即停止处理少于500个线程时,您将停止循环. 这是简单的代码

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

不幸的是,您会遇到其他问题,例如执行时间配额.在不超过配额的情况下,无法在一个呼叫中处理所有22000条消息.您必须监视执行时间并在脚本运行时间接近配额设置的时间(个人帐户运行时间为6分钟)时停止脚本,并使用ScriptApp.newTrigger(functionName)重新计划脚本以再次运行.您还必须在调用之间存储"startIndex"的值-考虑使用PropertiesService.

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.

这篇关于如何从Google脚本中的收件箱中读取所有邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆