I want to search email using Google App Script as 10 mins before to current time, I wrote the below script but it's not working, as I have emails with the same subject as defined in query and before 10 mins(even 1 min before mails are there) but GAS showing zero threads.
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);
}
This is accualy can be done, see the asnwer of @Iamblichus. Anyway, my method also works so I keep for the user to choose which method better for his needs.
A workaround to achive this goal:
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())
}
}
}
In Gmail search operators, before and after timestamps work with seconds, not with milliseconds.
Divide the timestamp by 1000, making sure it's an integer:
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);