Gmail Labeler script

Dynamic things like Categories need a little more work to label, because the label will stick around even after the category changes, or they’re not in the inbox anymore. We can add a step that removes the label from anything that no longer matches.

//Adam's sample configuration for "Gmail Filter by Search Query" https://gist.github.com/isiahmeadows/63716b78c58b116c8eb7

//Primary Category

//This example will add a label "primarycat" to any threads that are in my inbox and in the Primary category.
//It removes the label from anything that gets removed from the Primary category or from the inbox.
//It does this every ten minutes!  Then, Beeminder can pick up those labels.

//As of 2020, Beeminder's Gmail integration looks at labels and can't do arbitrary searches.  Most searches can be
//turned into a filter in Gmail that applies a label, but a few can't, like "older_than:".  This example
//uses an open source script to have Google search your email every ten minutes and apply labels.

//To set this up yourself, go to https://gist.github.com/isiahmeadows/63716b78c58b116c8eb7 and follow the directions.
//You can base your configuration off this one.

//As of December 30th, 2019, there's a small error in the source's Company label example.
//I've corrected it and hopefully it will be updated soon.

//If you get Invalid argument: label, you probably need to create the label first!
//You can do this in Gmail or via GmailApp.createLabel("labelname");

//Labeling based on dynamic features

//There are some dynamic email features, like Priority Inbox and Categories, that don't match
//labels, but we can map them to labels.

//In general, we build a query that maps to this dynamic feature.  We add the label to anything
//that matches this query, and then remove the label from anything that no longer matches the
//query.

const category = "primary";
const categoryLabel = "primarycat";

const labelQuery = "in:inbox category:" + category;
  
__setup({
    queries: [
      //Add the label to anything matching the query
      ["in:inbox category:" + category, function (thread) {
            thread.addLabel(GmailApp.getUserLabelByName(categoryLabel));
        }],
      //Remove the label to no longer matching the query
      ["-(" + labelQuery + ") label:" + categoryLabel,  function (thread) {
            thread.removeLabel(GmailApp.getUserLabelByName(categoryLabel));
        }],      
    ],
      
    notify: {
      // The email the script runs under--change it to your email.
        email: "CHANGETOYOUREMAIL@gmail.com",
        subject: "Filter Summary",
        body: "%c emails processed in the past 7 days.",
    },
});
1 Like