google apps script and GmailApp: get just new messages

Sorry for the late response but I just had the same type of problem and I ended up using GmailApp.search() ... hope this helps.

// find unread messages
var threads = GmailApp.search('is:unread');
....

WARNING

This call will fail when the size of all threads is too large for the system to handle. Where the thread size is unknown, and potentially very large, please use the 'paged' call, and specify ranges of the threads to retrieve in each call.

Take a look at GmailApp.search(query) and GmailApp.search(query, start, max)


Unfortunately there in no trigger that fires for each recieved message. There is however a good workaround:

Set up a filter rule that assigns a special label, "ToBeProcessedByScript" as example, to all incoming messages. Since wildcards don't really work in Gmail filters use the to: field.

Run a time-triggered script that collects all new message threads with GmailApp.getUserLabelByName("ToBeProcessedByScript").getThreads(). Remove the special label just before processing the new messages.