Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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:" subject:(Delivered)" },
{ age_min:"2d", age_max:"7d", query:"" },
{ age_min:"7d", age_max:"30d", query:" subject:(App Analytics Weekly Summary)" },
{ age_min:"7d", age_max:"30d", query:" subject:(coming up for renewal)" },
{ age_min:"2d", age_max:"7d", query:"" },
{ age_min:"7d", age_max:"30d", query:" 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 ="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());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment