Skip to content

Instantly share code, notes, and snippets.

Created January 8, 2017 16:39
Show Gist options
  • Save anonymous/2cca33d376f7f924fdaa67891ad098cc to your computer and use it in GitHub Desktop.
Save anonymous/2cca33d376f7f924fdaa67891ad098cc to your computer and use it in GitHub Desktop.
function gmailAutoarchive() {
var delayDays = 2; // will only impact emails more than 48h old
var maxDate = new Date();
maxDate.setDate(maxDate.getDate()-delayDays); // what was the date at that time?
// Get all the threads labelled 'autoarchive'
var label = GmailApp.getUserLabelByName("autoarchive");
var threads = label.getThreads(0, 400);
// we archive all the threads if they're unread AND older than the limit we set in delayDays
for (var i = 0; i < threads.length; i++) {
if (threads[i].getLastMessageDate()<maxDate)
{
threads[i].moveToArchive();
}
}
}
@cdunn95
Copy link

cdunn95 commented Jan 21, 2025

Thanks for this, I tweaked it for my needs and it is available here Archives any read message that is older than 24 hours.

Hi, I further tweaked your script and feel I made some worthwhile changes. A bit more verbose in the logging, but mainly it is more efficient in memory management and loops if the files to archive are >500. You can find the my updated version here.

Thanks for the starting point. :)

@ruckserve
Copy link

ruckserve commented May 21, 2025

Thank you for this gist and the Medium post. I modified to use the paginated call to GmailApp.search to only work on 50 conversations at a time, and simple forEach to archive them. here's my version:

function gmailAutoarchive() {
  var gmailFilter = "in:inbox label:autoarchive3d older_than:3d"
  var threads = GmailApp.search(gmailFilter, 0, 50);

  while (threads.length)  {
    Logger.log("found " + threads.length + " threads:");
    threads.forEach(thread => thread.moveToArchive());

    threads = GmailApp.search(gmailFilter, 0, 50);
  }
}

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