Skip to content

Instantly share code, notes, and snippets.

@stsquad
Created May 11, 2023 09:29
Show Gist options
  • Save stsquad/678ef18c3b962600df60dfa45b6b7570 to your computer and use it in GitHub Desktop.
Save stsquad/678ef18c3b962600df60dfa45b6b7570 to your computer and use it in GitHub Desktop.
Google App Script to cleanup my old lkml emails while keeping threads I'm in
/*
* Based on the original from http://www.skipser.com/p/2/p/auto-delete-email-in-any-gmail-label-.html
*
* Tweaked to keep messages from mythreads
*/
// The name of the Gmail Label that is to be checked for purging?
var LABEL_TO_DELETE = "kernel/lkml";
// But not these labels
var LABEL_TO_KEEP = "mythreads";
// Purge messages in the above label automatically after how many days?
var DELETE_AFTER_DAYS = "730";
function Intialize() {
return;
}
function Install() {
ScriptApp.newTrigger("deleteGmail")
.timeBased()
.at(new Date((new Date()).getTime() + 1000*60*2))
.create();
ScriptApp.newTrigger("deleteGmail")
.timeBased().everyDays(1).create();
}
function Uninstall() {
var triggers = ScriptApp.getProjectTriggers()();
for (var i=0; i<triggers.length; i++) {
ScriptApp.deleteTrigger(triggers[i]);
}
}
function deleteGmail() {
var age = new Date();
age.setDate(age.getDate() - DELETE_AFTER_DAYS);
var purge = Utilities.formatDate(age, Session.getTimeZone(), "yyyy-MM-dd");
var search = "(label:" + LABEL_TO_DELETE + " AND NOT label:" + LABEL_TO_KEEP +") before:" + purge;
try {
var threads = GmailApp.search(search, 0, 100);
if (threads.length == 100) {
ScriptApp.newTrigger("deleteGmail")
.timeBased()
.at(new Date((new Date()).getTime() + 1000*60*10))
.create();
}
for (var i=0; i<threads.length; i++) {
var messages = GmailApp.getMessagesForThread(threads[i]);
for (var j=0; j<messages.length; j++) {
var email = messages[j];
if (email.getDate() < age) {
email.moveToTrash();
}
}
}
} catch (e) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment