39
votes

I have created a Google Apps Script that checks if an email has an attachment then send it to another email address.

It's working fine, but I would like to create a trigger that would launch the script as soon as a new email arrives in the inbox.

I have been able to create a trigger that launch the script every hour, but it's not what I want

1
why not change it to launch every 5 minutes?Bryan P
I tried but I get a report at the end of the day saying that my scrip ran too many times. And it's not what I want, I want to run the script as soon I receive an emailAziCode
Spencer offered some sample code from this post after this announcementBryan P
That pubsub from Bryan P's comment looks interesting. Too bad there's not just an easy option to "run after each email" or what not. FWIW the most frequent it can trigger (if you go the trigger route) is "every minute" (and total cpu must be >= 90 min. per day)...rogerdpack
The blog post from Bryan P's comment went away when Google+ did, but the author has posted an updated example at github.com/Spencer-Easton/…Tripp Lilley

1 Answers

38
votes

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 See reference here.

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.