I'm trying to implement a simple google script that processes each message that is received by a Gmail user.
I've found an example that does something like this:
var threads = GmailApp.getInboxThreads();
for (var i=0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j=0; j < messages.length; j++) {
if (!messages[j].isUnread()) {
continue;
}
//process message
}
}
That is: I iterate through all messages in the inbox and search for the unread ones. This is very slow on just 1800 messages.
Ideally, I'm looking for a trigger that gets fired once each new message is received.
If there is no such thing, I would try to make use of this that I saw:
GmailApp.getMessageById(id)
I have extended the code with checking if the first message is really the one which is unread. If it is not it will check the next message and will continue untill it finds the unread message:
function getUnreadMails() {
var ureadMsgsCount = GmailApp.getInboxUnreadCount();
var threads;
var messages;
var k=1;
if(ureadMsgsCount>0)
{
threads = GmailApp.getInboxThreads(0, ureadMsgsCount);
for(var i=0; i<threads.length; i++)
{
if(threads[i].isInInbox())
{
messages = threads[i].getMessages();
for(var j=0; j<messages.length; j++)
{
while (messages[j].isUnread() === false)
{
threads=GmailApp.getInboxThreads(k, ureadMsgsCount);
messages = threads[i].getMessages();
k++;
}
Logger.log(messages[j].getSubject());
// process unread message
}
}
}
}
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With