Archive

Archive for July, 2013

Apply Gmail label to message that contains string in body

July 9th, 2013 No comments

Unfortunately gmail filters do not allow you to search just the body in a filter. IE body:myname is not valid. If your email address is first.last@some.com and you want to label all mail that contains First in the body, you cannot create a filter that works. You can however create a google apps script that will do it.

1. Go to https://script.google.com/, select Create script for Gmail.

2. Change label_name and name below then paste into google scripts.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function label_mention_in_body() {
  var label_name = 'YourLabel';
  var name = 'YourName';
  // I ignore name followed by . because 
  // my name is in my email address and I don't want that to count
  var regex = new RegExp(name + '[^.]', 'gi');
  // get all threads in inbox
  var threads = GmailApp.getInboxThreads();
  for (var i = 0; i < threads.length; i++) {
    // get all messages in a given thread
    var messages = threads[i].getMessages();
    // iterate over each message
    for (var j = 0; j < messages.length; j++) {
      var body = messages[j].getBody();
      if (body.match(regex)) {
        Logger.log("Adding label " + label_name + " to " + messages[j].getSubject() + " from " + messages[j].getTo());  
        var thread = messages[j].getThread();
        var label = GmailApp.getUserLabelByName(label_name);
        label.addToThread(thread);
      }
    }
  }
};

3. From the toolbar click Run -> label_mention_in_body

Assuming that did the right thing, you can now create a trigger to run this.

4. From the toolbar click Resources -> Current Project’s Triggers

5. Click add a new trigger. Change the drop downs to run every minute.

Done! It would be nice if you events could be OnNewMail or something, but this is better than nothing. I whipped this up pretty quick having never used google app scripts before. Pretty neat. Granted if this account had the ability for me to enable IMAP, I would have tried to set this sort of thing up with procmail.