Search code examples
javascriptgoogle-apps-scriptgmailgmail-api

Gmail search messages within a time period


I want to use google apps script to search messages within a time period. My current code looks like this:

let threads = GmailApp.search("newer_than:1h");
for (let i = 0; i < threads.length; ++i) {
  let messages = threads[i].getMessages();
  for (let ii = 0; ii < messages.length; ++ii) {
    foo(messages[ii]);
  }
}

The problem is that if a thread's latest message is received within 1 hour, all the messages in this thread will be returned. I know I can check the date of each message using messages[ii].getDate() to enforce each message called by foo() is within 1 hour. But is there any other way more direct to retrieve the messages within 1 hour? Is there an API similar to GmailApp.search() that works for messages?

Thanks


Solution

  • You can use the Gmail API to achieve that:

    1. Active the advanced service of the Gmail API
    2. Use the method described in Searching for Messages

    Sample:

    function searchMsgs() {
      msgs = Gmail.Users.Messages.list("me",{
        q: "newer_than:1h"
      })
      console.log(msgs)
    }