Automating Gmail Archive With Google App Scripts

What is Google App Scripts?

Before explaining what I did with Google App Scripts, let me explain what is Google App Scripts. It is basically a scripting engine that let you access all kinds of Google App features (including Gmail, Google Calendar, Google Docs, etc.). There are other ways to access these features but Google App Script might be the easist way out there. It comes with an online editor (you can work offline as well), and Google can trigger your scripts at certain time based on your need. Oh, forgot to mention, Google App Script uses JavaScript which is one of the most popular languages right now (Sadly, it doesn't support ES6 syntax as of writing).

Why use Google App Scripts?

I have a habit of archiving my Emails every week on Mondays. It is easy enough to do in the gmail Web interface but I do need to remember to do it. That make me think if I can find a good way to automate this. I would always think of using some kind of API first, but it seems to me that it wouldn't worth it to spend time to make a app just for the purpose of archiving emails. Then I came across Google App Scripts, which turned out to be exactly what I need to automate this.

What I came up with

Here is what I came up with to archive emails that are one-week-old every Monday at midnight:

1
2
3
4
5
6
7
8
9
10
11
function gmailAutoarchive() {
var maxDate = new Date();
// Archive all threads in inbox whose last message date is older than today.
var threads = GmailApp.getInboxThreads();
for(var i in threads){
var thread = threads[i];
if (thread.getLastMessageDate()<maxDate){
thread.moveToArchive();
}
}
}

You will be able to use this script by putting it into the google script editor located here.

To have Google auto run your scripts, you need to add the trigger which can be found under Edit --> Current project's triggers.

Variation

After creating this script, I created another script as a variation to this script that move messages with certain labels to trash.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function gmailAutoRemove() {
var maxDate = new Date();
maxDate.setDate(maxDate.getDate() - 30); // what was the date at that time?
var label = [GmailApp.getUserLabelByName("label1"), GmailApp.getUserLabelByName("label2"), GmailApp.getUserLabelByName("label3")];
label.forEach(removeByLabel(maxDate));
}


function removeByLabel(maxDate){
return function(label){
var threads = label.getThreads(0, 100);
for(var i in threads){
var thread = threads[i];
if (thread.getLastMessageDate() < maxDate){
thread.moveToTrash();
}
}
}
}

References: Auto archive emails in Gmail after 2 days