How to trigger function when new email arrives in Gmail?

I want to automatically execute a custom function each time a new message lands in my Gmail inbox. I’ve been checking the Google Apps Script documentation for event triggers but can’t find any specific trigger that fires when an email is received. Is there a way to set up this kind of email arrival detection? I need to process incoming emails as soon as they arrive. Maybe there’s a different approach I should be using? I’m wondering if I missed something in the trigger options or if there’s another method to monitor new emails in real time.

Google Apps Script currently does not provide a trigger that activates upon the arrival of a new email in Gmail. I encountered this limitation while developing an email processing solution last year. To work around it, I implemented a time-driven trigger that executes every minute to check for new messages via GmailApp.search() with a timestamp filter. This method scans for emails received in the last few minutes, using PropertiesService to track processed message IDs to avoid duplicates. Although it lacks real-time capabilities, it effectively meets most needs. Alternatively, for a more complex solution, consider leveraging Gmail’s push notifications with Cloud Pub/Sub, which might be too intricate for basic tasks.

There isn’t a built-in trigger for new emails in Gmail through Google Apps Script. I faced similar frustrations when trying to create an email monitoring tool. A practical solution I found was to use a time-driven trigger that runs every 5 minutes to check for new unread emails that fit your criteria. By using GmailApp.getInboxThreads(), you can retrieve the latest threads, subsequently filtering them to ensure you haven’t processed them already. Managing the IDs of processed emails is crucial, whether using a spreadsheet or PropertiesService, to avoid duplicates. While this approach isn’t instantaneous, it effectively suits many business needs. Adjust the check frequency but be mindful of the usage limits imposed by Google.

unfortuately there’s no direct way to catch new emails instantly. I use a workaround with time triggers every 2-3 mins checking for recent messages using search queries like ‘is:unread newer_than:5m’. Works decently enough for most cases tho not truly real-time.