Reputation: 2995
Is it possible to retrieve all Gmail messages received after a particular date directly without going through all messages?
Currently, I am using GmailApp.getInboxThreads(0, 50)
function to retrieve the first 50 threads and then loop through all the threads for finding the messages satisfying the condition. But what if there are more than 50 threads satisfying the condition? So fetching emails with GmailApp.getInboxThreads(start, max)
function isn't a perfect solution.
The getInboxThreads()
function seems good but it could fail when the size of all threads is too large for the system to handle.
Also, it should fetch all emails except ones from the spam folder.
Here is the code I use.
var gmailThreads = GmailApp.getInboxThreads(0, 50);
for (var i = 0; i < 50; i++) {
var messages = gmailThreads[i].getMessages();
for (var j = 0; j < messages.length && (messages[j].getDate().valueOf() > requiredDate.valueOf()); j++) {
//Loop Content
}
}
Upvotes: 0
Views: 2466
Reputation: 19835
use search, specifying a start date. https://developers.google.com/apps-script/reference/gmail/gmail-app#search(String)
Thou undocumented, you can search also by date+time with a resolution of 1 second because the date operators like "before" and "after" accept unix timestamps.
One lame issue with that apps script api is that it returns threads, not messages, and requires looping potentially long threads woken up by a new message, making it less robust as it can be time consuming to deal with those old messages. Gmail advanced api from apps script advanced services does have another message-level search api that wont have that issue.
Upvotes: 3