How to trigger a Google Apps Script once an email get in the inbox?

Solution 1:

After some research and some help from other google-apps-script developers, the best solution is to use a combination of Gmail filtering system in addition to a time-driven-trigger.

So basically for a normal Gmail account there is a 1 hour/day computing time as mentioned in the documentation.

So what I did is set up a filter that adds a Label and a star to the incoming emails that need to be processed.

In my script I add the Labels in an array, I loop over the array of labels so that I process only the desired emails and not the whole inbox.

Once processed, the script removes the star from the processed email.

This way you don't lose your precious compute time, and you don't reach the daily limit.

I then set a time driven trigger that runs every 10 minutes.

You can also set up the time driven trigger to send you a daily "Summary of failures " so that you can see what went wrong with your script and fix what has to be fixed.

Solution 2:

This answer is adapted from the answer of @AziCode but includes code.

Components of the solution:

  • A code-free Gmail filter that catches emails with the desired condition; for actions choose “star it” and “apply the label” (enter your desired label)
  • A trigger configured to run often; this trigger loops through your emails, catching ones that are starred and have the label, performing your desired action on them, and then removing the star.

Here’s the code to have in your Google Apps Script project (you must give the script permission to access your GMail inbox):

// Configure this trigger to run often
// (*how* often depends on the desired response time *and* how willing you are to risk hitting Google Apps Script’s rate limits;
// 10 minutes is probably good)
function triggerScriptForEmail() {
  const threads = GmailApp.search('is:starred label:"<your desired label>"');

  for (const thread of threads) {
    const messages = thread.getMessages()

    for (const message of messages) {
      // we know the thread *has* starred messages, but not *all* messages are necessarily starred
      if (message.isStarred()) {
        // THE CODE SPECIFIC TO YOUR CASE GOES HERE
        // THEN...
        message.unstar()
      }
    }
  }
}