Last active
June 16, 2024 21:11
-
-
Save Mr0grog/98946a33bd41daf2f7688e79875d6016 to your computer and use it in GitHub Desktop.
GMail Cleanup (Google Apps Script)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Delete e-mails older than N days based on their label(s). | |
* Starred/flagged e-mails are never deleted. | |
* | |
* Set this up as a project at https://script.google.com/ | |
* And create a trigger that runs `cleanUpMailers` every hour. | |
*/ | |
var DAY = 24 * 60 * 60 * 1000; | |
// Maps a label to how many to expire its messages after. | |
const expirationDays = { | |
"_expire/ultrafast": 1, | |
"_expire/fast": 7, | |
"_expire/med": 14, | |
"_expire/slow": 31, | |
"np-activism": 7, | |
"_newsdaily": 5, | |
}; | |
function cleanUpTest () { | |
cleanUpMailers({dryRun: true}); | |
} | |
function cleanUpMailers ({ dryRun = false } = {}) { | |
const now = new Date(); | |
for (const [labelName, days] of Object.entries(expirationDays)) { | |
const maxTime = new Date(now - days * DAY) | |
const label = GmailApp.getUserLabelByName(labelName); | |
if (!label) { | |
console.warn(`No label named "${labelName}"`); | |
continue; | |
} | |
for (const thread of label.getThreads()) { | |
const threadTime = thread.getLastMessageDate(); | |
if (threadTime < maxTime && !thread.hasStarredMessages()) { | |
console.log(`Dropping thread "${thread.getFirstMessageSubject()}" (Updated: ${threadTime})`); | |
if (!dryRun) { | |
thread.moveToTrash(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment