Google gmail script that triggers on incoming email

You can't create a trigger for every email, however you can do something similar as described in this answer.

For example you can:

  1. Set up a filter that puts a special label on incoming emails that you want to process.

  2. Set up a reoccurring script that runs every 10 minutes, or even every minute. In the script, you can pull all of the emails that have the given label, and process them accordingly, removing the label when you are done.

function processEmails() {
  var label = GmailApp.getUserLabelByName("Need To Process");
  var threads = label.getThreads();  
  for (var i = threads.length - 1; i >= 0; i--) {
    //Process them in the order received
    threads[i].removeLabel(label).refresh();
  }
}

You can then set this on a time based trigger to have it run as often as you would like.

If you want to keep track of the emails you have processed, you can create another "processed" label and add that to the message when you are done processing.


I had a little trouble with getting the labels right so I'm including code to log your labels. I modified user3312395's code also to add new label also. Thanks for the original answer too!

function emailTrigger() {

  var label = GmailApp.getUserLabelByName('Name of Label to Process');
  var newLabel = GmailApp.getUserLabelByName('New Label Name');

  if(label != null){
    var threads = label.getThreads();
    for (var i=0; i<threads.length; i++) {
      //Process them in the order received
      threads[i].removeLabel(label);
      threads[i].addLabel(newLabel);
      //run whatever else here
    }
  }

}

function getLabels(){
  var labels = GmailApp.getUserLabels();
  for(i=0; i<labels.length; i++){
    Logger.log(labels[i].getName());
  }
}