-
-
Save klinquist/78f81e55c094111a9d3ba675c3bfd3a0 to your computer and use it in GitHub Desktop.
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
// A better version of this script: https://pixelbakery.com/recipes/gmail-automatically-delete-or-archive-emails | |
// Enhancements by Kris Linquist: | |
// - Uses gmail's search feature to automatically return emails older than a date rather than returning | |
// all mail and comparing the date of the email | |
// - Loops until there are no more results - gmail's API only returns 500 emails at a time. | |
function autoDelete() { | |
var deleteEmailsOlderThanDays = 3; | |
var deleteEmailsWithThisLabel = 'GitHub'; | |
function getDateBeforeToday(daysBefore) { | |
let today = new Date(); | |
// Subtract the specified number of days | |
today.setDate(today.getDate() - daysBefore); | |
// Extract year, month, and day | |
let year = today.getFullYear(); | |
let month = today.getMonth() + 1; // Months are zero-based | |
let day = today.getDate(); | |
// Format month and day with leading zero if needed | |
month = month < 10 ? '0' + month : month; | |
day = day < 10 ? '0' + day : day; | |
// Return the formatted date | |
return `${year}/${month}/${day}`; | |
} | |
console.log('Started autoDelete run.'); | |
var query = `label:${deleteEmailsWithThisLabel} before:${getDateBeforeToday(deleteEmailsOlderThanDays)}` | |
var threads; | |
var counter = 0; | |
var errors = 0; | |
do { | |
Logger.log(`Searching with query ${query}`) | |
threads = GmailApp.search(query); | |
if (threads.length > 0) { | |
console.log('Found ' + threads.length + ' emails marked for deletion.'); | |
try { | |
for (var i = 0; i < threads.length; i++) { | |
try { | |
threads[i].moveToTrash(); | |
Logger.log(`Deleted email: ${threads[i].getFirstMessageSubject()} with date ${threads[i].getLastMessageDate()}...`); | |
counter++; | |
} catch (e) { | |
Logger.log(`Error moving thread to trash: ${threads[i].getFirstMessageSubject()}`); | |
} | |
} | |
} catch (e) { | |
errors++; | |
console.error(`Could Not Complete Run: ${e}`); | |
} | |
} else { | |
console.log('No emails marked for deletion. Exiting.'); | |
} | |
} while (threads.length > 0); | |
console.log(`Successfully moved ${counter} emails to the trash with ${errors} errors.`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment