Reputation: 201
I am trying to get no of emails for yesterday according to one particular subject. Usually, what I do at midnight 1 o'clock I count the no of emails for a particular subject and send the mail through Google script. At 3 o'clock I trigger one delete trigger which starts deleting mail of previous day. so by this, I ensure I don't have any mail for the previous day.
var yesterday = "2017/7/10";
var today = "2017/7/11";
var query = "after:"+yesterday+" before:"+today+" subject: abcd";
To count no of emails I have written below function
function getEmailCount(query) {
var threads = GmailApp.search(query, 0, 500);
Logger.log(threads);
var total = 0;
for (var i = 0; i < threads.length; i++) {
var messagesInThread = threads[i].getMessageCount();
var msg = threads[i].getMessages()[0].getSubject()
total = total + messagesInThread;
}
Logger.log(msg)
Logger.log("Query %s", query);
Logger.log("No. Of Threads %s", threads.length);
Logger.log("No. Of Emails %s", total);
return total;
}
When I check for emails in Gmail with above subject I get only 8 but my script is returning 25 mails. Any help will be highly appreacated .
Upvotes: 1
Views: 1031
Reputation: 4034
It is interesting, GMailApp
does return some emails within threads outside of the search parameters that the Gmail web app was not. I have a suspicion this was a time-zone related thing due to the nature of the specific emails I was looking at.
Some modifications to your code can add for a couple of checks that differentiate the raw results and some of the UX that the web app throws in for free. Additionally, this filters threads and messages that strictly adhere to the search criteria.
function getEmailCount(query) {
var yesterday = "2017/06/07",
today = "2017/06/08",
yesterdayDate = new Date(yesterday),
todayDate = new Date(today);
query = query || "after:" + yesterday + " before:" + today + "";
var threads = GmailApp.search(query).reduce(function(validThreads, thread, idx) {
var messages = thread.getMessages().reduce(function(messages, message, idx) {
var isChat = message.isInChats(),
isDeleted = message.isInTrash(),
sent = message.getDate();
if (!isDeleted && !isChat && sent < todayDate && sent > yesterdayDate) {
messages.push(message.getSubject());
}
return messages;
}, []);
if (messages.length > 0) { validThreads[idx] = messages; }
return validThreads;
}, {});
var totalMessages = Object.keys(threads).reduce(function(count, thread) {
return count += threads[thread].length;
}, 0);
Logger.log("Query: %s", query);
Logger.log("No. Of Threads: %s", Object.keys(threads).length);
Logger.log("No. Of Emails: %s", totalMessages);
return totalMessages;
}
Upvotes: 1