Skip to content

Instantly share code, notes, and snippets.

@metacurb
Created October 24, 2025 15:53
Show Gist options
  • Select an option

  • Save metacurb/2211c4f01c60042976515334875b2d56 to your computer and use it in GitHub Desktop.

Select an option

Save metacurb/2211c4f01c60042976515334875b2d56 to your computer and use it in GitHub Desktop.
An AppScript to automatically delete your gmail emails on a rolling window.
const RETENTION_DAYS = 30
function deleteOldEmails() {
const maxDate = new Date();
maxDate.setDate(maxDate.getDate() - RETENTION_DAYS);
const formattedDate = Utilities.formatDate(maxDate, Session.getScriptTimeZone(), 'yyyy/MM/dd');
const query = 'before:' + formattedDate;
Logger.log('--- Gmail Cleanup Started ---');
Logger.log('Query: ' + query);
Logger.log('Running at: ' + new Date());
// Search for old threads
const threads = GmailApp.search(query);
Logger.log('Found ' + threads.length + ' threads to delete (older than ' + RETENTION_DAYS + ' days).');
let deletedCount = 0;
const batchSize = 100;
for (let i = 0; i < threads.length; i += batchSize) {
const batch = threads.slice(i, i + batchSize);
GmailApp.moveThreadsToTrash(batch);
deletedCount += batch.length;
Logger.log('Deleted batch ' + (i / batchSize + 1) + ': ' + batch.length + ' threads.');
}
Logger.log('Total deleted: ' + deletedCount + ' threads.');
Logger.log('Cleanup finished at: ' + new Date());
Logger.log('-----------------------------');
}
@metacurb
Copy link
Author

I migrated away from gmail a long time ago, and have emails forwarded to new provider. I don't particularly want any data kept within my gmail account, and the end goal is to disconnect from gmail entirely.

I have set this script up as a project in Apps Script, and the trigger will run this function every day at around midnight.

Set RETENTION_DAYS to your preferred retention period.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment