Gmail – How to Filter Emails by Specific ‘via’ Tag

gmailgmail-filters

I want to filter my Gmail emails by a specific via tag.

Let's say the tag is examplewebsite.edu.com and the email sender is someperson@example.com

I want to filter every email, irrelevant of the sender, if there is a via exapmlewebsite.edu.com

someperson@example.com via examplewebsite.edu.com.

Note that I don't want to delete these emails, I want them to be labeled and get pushed into the according section of my Gmail account.

Best Answer

Edited the script provided by @serenesat's comment to instead of filtering and deleting all the messages, now attaches a label to them and puts them into that directory.

    function filterByVia() {
      var threads = GmailApp.getInboxThreads(0, 5);
      var label = GmailApp.getUserLabelByName("yourlabel");
      for (var i = 0; i < threads.length; i++) {
        var messages=threads[i].getMessages();
        for (var j = 0; j < messages.length; j++) {
          var message=messages[j];
          var body=message.getRawContent();
          if (body.indexOf("the domain after via") > -1) {
            label.addToThread(threads[i]);
          }
          Utilities.sleep(1000);
        }

       }
     }