Write Gmail Filters with Google Apps Script

The Google Script uses regular expressions to create advanced Gmail filters that works just like the native filters of Gmail but are more powerful at parsing email.

Perform case-sensitive search for Gmail

function rule0(thread, rule) {
  var msg = thread.getMessages()[0];
  var body = stripTags([msg.getSubject(), msg.getBody()].join());
  var regex = new RegExp(rule[2], 'g');
  if (body.match(regex)) {
    thread.addLabel(getGmailLabel(rule[1]));
  }
}

Is the email sent to several people at once

function rule1(thread, rule) {
  var msg = thread.getMessages()[0];
  var to = [msg.getTo(), msg.getCc()].join();
  if (to.match(/@/g).length >= rule[2]) {
    thread.addLabel(getGmailLabel(rule[1]));
  }
}

Is the email extremely long (count words)

function rule3(thread, rule) {
  var msg = thread.getMessages()[0];
  var body = stripTags(msg.getBody());
  if (body.match(/\s+/g).length >= rule[2]) {
    thread.addLabel(getGmailLabel(rule[1]));
  }
}

Does the message have too many attachments?

function rule5(thread, rule) {
  var msg = thread.getMessages()[0];
  var att = msg.getAttachments();
  if (att.length > rule[2]) {
    thread.addLabel(getGmailLabel(rule[1]));
  }
}
function rule7(thread, rule) {
  var msg = thread.getMessages()[0];
  var body = msg.getBody();
  if (body.match(/\https?:\/\//g).length > rule[2]) {
    thread.addLabel(getGmailLabel(rule[1]));
  }
}

Does a message contain too many images?

function rule8(thread, rule) {
  var msg = thread.getMessages()[0];
  var body = msg.getBody();
  if ((body.match(/<img[^>]+>/g) || []).length > rule[2]) {
    thread.addLabel(getGmailLabel(rule[1]));
  }
}
Amit Agarwal

Amit Agarwal

Google Developer Expert, Google Cloud Champion

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.

Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Awards & Titles

Digital Inspiration has won several awards since it's launch in 2004.

Google Developer Expert

Google Developer Expert

Google awarded us the Google Developer Expert award recogizing our work in Google Workspace.

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards in 2017.

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional (MVP) title for 5 years in a row.

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator title recognizing our technical skill and expertise.

Email Newsletter

Sign up for our email newsletter to stay up to date.

We will never send any spam emails. Promise.