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]));
  }
}

/* Does a message contain too many links? */
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]));
  }
}