使用 Google 应用程序脚本从当前时间前 10 分钟获取电子邮件

Get Emails from Gmail using Google App Script as 10 mins before to current time

我想使用 Google App Script 搜索当前时间之前 10 分钟的电子邮件,我编写了以下脚本但它不起作用,因为我有与查询中和之前定义的主题相同的电子邮件10 分钟(甚至在邮件到达之前 1 分钟)但 GAS 显示零线程。

function testforemails(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Emails");
  var Gmail = GmailApp;
  var lasttime = sheet.getRange("Z1").getValue(); // it will use later as the time of last searched email.
  Logger.log(lasttime);
  var cdate = new Date();
  var ctime = cdate.getTime();
  var qDate = new Date(ctime - 600000); // less 10 minutes from current time.
  Utilities.formatDate(qDate, Session.getScriptTimeZone(), "dd-MMM-yy hh:mm a")
  Logger.log("QDATE IS " + qDate); //  perfectly displaying time less than 10 minutes
  var qtime = qDate.getTime();
  Logger.log("qtime is " + qtime);

  // SEARCH EMAIL
  var query = 'subject: defined subject of emails, after:' + (qDate);
  var threadsNew = Gmail.search(query);
  Logger.log(threadsNew.length);
  var folderid = 'define folder id'
  var folder = DriveApp.getFolderById(folderid);
  for(var n in threadsNew){
    var thdNew  = threadsNew[n]; 
    var msgsNew = thdNew.getMessages(); 
    var msgNew = msgsNew[msgsNew.length-1];
  // GET ATTACHMENT
    var bodyNew = msgNew.getBody();
    var plainbody  = msgNew.getPlainBody();
    var subject = msgNew.getSubject();
    var Etime = msgNew.getDate();
    var attachments = msgNew.getAttachments();
    var attachment = attachments[0];
    
    Logger.log(Etime);
    Logger.log(subject);
  }
    
    Logger.log(threadsNew.length);
    
    
}

更新

这个是可以做到的,看@Iamblichus的回答。反正我的方法也管用,留给用户自己选择更适合自己的方法。


实现此目标的解决方法:

function testforemails(){
  // SEARCH EMAIL
  let now = new Date();
  let query = 'subject: YOUR_SUBJECT, after:' + now.toISOString().slice(0, 10); // find mails from today
  console.log(query);
  let threadsNew = GmailApp.search(query);
  console.log("threadsNew.length: " + threadsNew.length);

  for(let thread of threadsNew){
    let lastMsgTime = thread.getLastMessageDate();
    let tenMinutesAgo = new Date(now - 600000);

    if(lastMsgTime - tenMinutesAgo > 0) { // if the last message on the thread was less than 10 minutes ago
      // do your magic here
      console.log(thread.getLastMessageDate())
    }  
  }    
}

问题:

在 Gmail 搜索运算符中,beforeafter 时间戳以秒为单位,而不是以毫秒为单位。

解决方案:

将时间戳除以 1000,确保它是一个整数:

function testforemails(){
  var cdate = new Date();
  var ctime = cdate.getTime();
  var qDate = new Date(ctime - 600000); // less 10 minutes from current time.
  var query = 'after:' + Math.floor(qDate.getTime()/1000);
  var threadsNew = GmailApp.search(query);
  Logger.log(threadsNew.length);
  // ...
}

其他问题:

  • 在您的查询中,您直接提供了日期,没有转换为毫秒数。这行不通:
var qDate = new Date(ctime - 600000);
var query = 'subject: defined subject of emails, after:' + (qDate);

相关: