Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google apps script and GmailApp: get just new messages

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)
like image 206
AgostinoX Avatar asked Oct 16 '12 21:10

AgostinoX


2 Answers

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
          }
       }
     }
   }
 }
like image 63
deepwell Avatar answered Nov 16 '22 03:11

deepwell


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)

like image 37
djtek Avatar answered Nov 16 '22 03:11

djtek