Discrepancy in Gmail search results using GmailApp

I’m trying to use the GmailApp search function in Google Apps Script, but I’m getting weird results. Here’s what’s happening:

When I run this code:

var sent_threads = GmailApp.search('in:sent after:2016/02/29');
Logger.log(sent_threads.length);

for (var i = 0; i < sent_threads.length; i++) {
  var message = sent_threads[i].getMessages()[0];
  var recipient = message.getTo();
  Logger.log(recipient);
}

It shows 21 threads and logs 21 email recipients. But when I use the same search query directly in Gmail, I get 44 messages.

Why are the results different? Am I missing something about how GmailApp search works compared to the regular Gmail search? Any help would be great because this is really confusing me.

I’ve encountered similar discrepancies when working with GmailApp searches. In my experience, GmailApp sometimes groups messages into conversations, which can result in a lower count compared to a direct Gmail search. There might also be a delay in how emails are synced between the script and the Gmail interface, and it’s possible that the search criteria are interpreted in slightly different ways by each system. To troubleshoot this, I recommend refining your search by adding more parameters such as a sender or subject. If you require more precise results, using the Gmail API could provide better accuracy.

I’ve run into this issue before. One key difference is that GmailApp.search() returns threads, not individual messages. So if you have multiple messages in a single thread, they’ll be counted as one result. This can lead to discrepancies compared to Gmail’s interface search.

To get a more accurate count, you might try iterating through the threads and counting the total messages:

var totalMessages = 0;
sent_threads.forEach(function(thread) {
  totalMessages += thread.getMessageCount();
});
Logger.log(totalMessages);

This should give you a number closer to what you see in Gmail. Also, keep in mind that there might be slight delays in syncing between GmailApp and the actual Gmail interface, which could contribute to the difference in results.

yeh, i’ve seen this too. GmailApp can be weird sometimes. it might be grouping stuff differently or not catching everything. have you tried playing with the search terms? maybe add some keywords or change the date range a bit. could help narrow things down. good luck!