Write Gmail Filters with Google Apps Script

W
Published in: Gmail - 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]));
  }
}
Published in: Gmail - Google Apps Script

Looking for something? Find here!

Meet the Author

Web Geek, Google Developer Expert
A
Amit Agarwal

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. He is the developer of Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Get in touch