Auto-Archive Old Emails in Gmail Using Apps Script

A cluttered inbox kills productivity. Instead of manually archiving old emails, you can automate the entire process with a Google Apps Script that runs on a schedule.

How archiving works in Apps Script

In Gmail, "archiving" means removing the Inbox label from a thread. Apps Script gives you access to GmailApp, which lets you search threads and remove that label programmatically.

Archive emails older than 30 days

This script finds all inbox emails older than 30 days and archives them:

function archiveOldEmails() { const daysOld = 30; const query = `in:inbox older_than:${daysOld}d`; const threads = GmailApp.search(query); if (threads.length === 0) { Logger.log('No old emails to archive.'); return; } GmailApp.moveThreadsToArchive(threads); Logger.log(`Archived ${threads.length} thread(s).`); }

GmailApp.search() accepts the same search operators as the Gmail search bar, so you can get very specific about what to archive.

Archive by label

If you use labels to organise emails, you can target a specific label:

function archiveLabelledEmails() { const labelName = 'Newsletters'; const daysOld = 7; const query = `label:${labelName} older_than:${daysOld}d`; const threads = GmailApp.search(query); GmailApp.moveThreadsToArchive(threads); Logger.log(`Archived ${threads.length} "${labelName}" thread(s).`); }

Archive emails from specific senders

function archiveFromSender() { const senders = ['[email protected]', '[email protected]']; senders.forEach(sender => { const query = `from:${sender} in:inbox older_than:14d`; const threads = GmailApp.search(query); if (threads.length > 0) { GmailApp.moveThreadsToArchive(threads); Logger.log(`Archived ${threads.length} thread(s) from ${sender}`); } }); }

Run it on a schedule with a Time-based Trigger

To make this fully automatic, set up a daily trigger:

function createDailyTrigger() { ScriptApp.newTrigger('archiveOldEmails') .timeBased() .everyDays(1) .atHour(7) // Runs at 7 AM .create(); }

Run createDailyTrigger() once from the Apps Script editor, and your inbox will be cleaned up every morning automatically.

Tips

  • Gmail's search() returns a maximum of 500 threads per call. If you have more, paginate using the second and third arguments: GmailApp.search(query, start, max).
  • Always test your search query in the Gmail search bar before running it in a script to avoid accidentally archiving important emails.
  • You can combine search operators: in:inbox older_than:30d -is:starred to skip starred emails.