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 is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

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

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

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

We will never send any spam emails. Promise 🫶🏻