Created
November 14, 2018 19:18
-
-
Save garrow/ec1244a92a7a8e31ee785b3202db0baf to your computer and use it in GitHub Desktop.
gmail-query-auto-archiver
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
function main() { autoArchiveMail() } | |
// A mapping of a query / saved search, and the ageCutoff for archiving. | |
function archiveMap() { | |
return [ | |
{query: inbox('label:expirable label:stripe'), ageCutoff: hoursOld(1)}, // Quickly burn these | |
{query: inbox('"Your meeting attendees are waiting!"'), ageCutoff: hoursOld(1)}, // Quickly burn these | |
{query: inbox('label:n'), ageCutoff: hoursOld(6)}, | |
{query: inbox('label:expirable'), ageCutoff: hoursOld(6)}, | |
{query: inbox('label:office'), ageCutoff: daysOld(10)}, // Offce Notices | |
] | |
} | |
// The catch-all label to put on mail you don't need to keep around. | |
function expireLabel() { | |
return 'expirable'; | |
} | |
// The label which marks mail as having been processed by this script. | |
function expiredLabel() { | |
return 'expired'; | |
} | |
// A safe base query builder that | |
// - includes mail in the Inbox | |
// - excludes starred email | |
// - excludes TODO mails | |
function inbox(extras) { | |
return 'in:inbox -label:todo -is:starred ' + extras; | |
} | |
function autoArchiveMail() { | |
var archivals = archiveMap(); | |
archivals.forEach(archive); | |
} | |
function archive(mapping) { | |
Logger.log("Archiving %s", mapping); | |
var archivalThreads = GmailApp.search(mapping.query, 0, 400); | |
var selectorLabel = GmailApp.getUserLabelByName(expireLabel()); | |
var markerLabel = GmailApp.getUserLabelByName(expiredLabel()); | |
archivalThreads.forEach(function (currentThread) { | |
if (currentThread.getLastMessageDate() < mapping.ageCutoff) { | |
markerLabel.addToThread(currentThread); | |
currentThread.moveToArchive(); | |
selectorLabel.removeFromThread(currentThread); | |
} | |
}); | |
} | |
function hoursOld(hoursAgo) { | |
var cutOff = new Date(); | |
cutOff.setHours(cutOff.getHours() - hoursAgo); | |
return cutOff; | |
} | |
function daysOld(daysAgo) { | |
var maxDate = new Date(); | |
maxDate.setDate(maxDate.getDate() - daysAgo); | |
return maxDate; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment