Home

My first blog post: archiving old emails

Context:

I use my inbox as a:

  • way to alert me
  • todo list

The problem

My inbox gets full quickly if I don't clear it up every day I like to use filters to clear up my inbox automatically Unfortunately there is no way to add time based criteria in gmail filters

The solution

Write a Google script to add the time-based labels. If you want the step-by-step recipe, reach out to me. I want to get to know my audience

The code

There are 2 files:

  • domain_logic.js: If I were using a different email provider I would probably not change this code
  • implementation_details.js: this the code specific to Google script

Important disclaimer

This code is still WIP. There are still some issues with it. Check back later after it has been hardened by usage

domain_logic.js file

/**
domain_logic.js
===============
Define here how many time-based labels you want
if you have [1,7,14] your emails will have the following labels:
- `time_based_labels/1_day_old`
- `time_based_labels/7_days_old`
- `time_based_labels/14_days_old`
*/
const time_based_labels_to_add = [
1,
7,
14
]
/**
This is the method that we are going to trigger every day to label all emails in your inbox
*/
function assign_time_based_labels_to_emails() {
create_labels_if_they_dont_exist()
var threads = get_email_threads()
threads.forEach(thread => {
time_based_labels_to_add.forEach(x => {
if(is_x_days_old(x)(thread)){
assign_x_days_old_label(x)(thread)
}
})
})
}
/**
This is a convenience method that creates the labels if they don't exist yet
*/
const create_labels_if_they_dont_exist = () => {
time_based_labels_to_add.forEach(nbr_day => {
const label_name = create_x_days_old_label_name(nbr_day)
const label = get_label_by_name(label_name)
if(label === null){
create_label(label_name)
}
})
}
/**
Tells you if thread is x days old
*/
const is_x_days_old = x => thread => {
const today = new Date()
const date_x_days_ago = today.setDate(today.getDate()-x)
return thread.getLastMessageDate() < date_x_days_ago
}
const create_x_days_old_label_name = x => {
const s = x === 1 ? '' : 's'
return `time_based_labels/${x}_day${s}_old`
}
/**
Assigns the time based label to the thread
*/
const assign_x_days_old_label = x => thread => {
const label_x_days_old = get_label_by_name(create_x_days_old_label_name(x))
label_x_days_old.addToThread(thread)
}

implementation_details.js

/**
Keep the boring implementation emails separate from the main logic
*/
const create_label = label_name => GmailApp.createLabel(label_name)
const get_label_by_name = label_name => GmailApp.getUserLabelByName(label_name)
const get_email_threads = () => GmailApp.getInboxThreads()