Skip to content

Instantly share code, notes, and snippets.

@cmsj
Created August 4, 2020 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmsj/ccc7e7b60661a705c1003788436382fe to your computer and use it in GitHub Desktop.
Save cmsj/ccc7e7b60661a705c1003788436382fe to your computer and use it in GitHub Desktop.
Gmail scripting example
// Configuration data
// Each config should have the following keys:
// * age_min: maps to 'older_than:' in gmail query terms.
// This is how old you want matching emails to be before they are archived.
// * age_max: maps to 'newer_than:' in gmail query terms.
// This is how far back in history you want to search, to find emails to archive.
// It's useful to set fairly long for your first run, but after that set it to a
// reasonably low value (don't expect Google to search your entire email archive
// every time this script runs!)
// * query: freeform gmail query terms to match against
//
// Why do the age_min/age_max keys exist, given the freeform query value?
// Well, age_min forces you to think about how frequent the emails are, and age_max
// forces you to not search for every single email tha matches the query
//
// TODO:
// * Add a per-config flag that skips the archiving if there's only one matching thread (so the most recent matching email always stays in Inbox)
var configs = [
{ age_min:"14d", age_max:"90d", query:"subject:(Benedict's Newsletter)" },
{ age_min:"1d", age_max:"7d", query:"from:Amazon subject:(Arriving today)" },
{ age_min:"1d", age_max:"30d", query:"from:Amazon.co.uk subject:(Delivered)" },
{ age_min:"2d", age_max:"7d", query:"from:notification@istheapplestoredown.com" },
{ age_min:"7d", age_max:"30d", query:"from:appstoreconnect-noreply@apple.com subject:(App Analytics Weekly Summary)" },
{ age_min:"7d", age_max:"30d", query:"from:help@hover.com subject:(coming up for renewal)" },
{ age_min:"2d", age_max:"7d", query:"from:PurchaseSupport@twitch.tv" },
{ age_min:"7d", age_max:"30d", query:"from:noreply@github.com subject:(Your Dependabot alerts)" },
{ age_min:"7d", age_max:"30d", query:"from:Apple subject:(Your invoice from Apple)" },
];
function processInbox() {
for (var config_key in configs) {
var config = configs[config_key];
Logger.log("Processing query: " + config["query"]);
var threads = GmailApp.search("in:inbox " + config["query"] + " newer_than:" + config["age_max"] + " older_than:" + config["age_min"]);
for (var thread_key in threads) {
var thread = threads[thread_key];
Logger.log(" Archiving: " + thread.getFirstMessageSubject());
thread.markRead();
thread.moveToArchive();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment