March 3rd, 2025
How to Automatically Delete Old Gmail Emails with Google Apps Script
Clean up your Gmail inbox automatically. Learn how to schedule and run a simple Apps Script to delete older or unwanted emails in bulk.
Emails pile up quickly, making it easy to lose track of important messages. If your inbox is cluttered with old promotions and updates, you can automatically delete or archive them using a short Google Apps Script. This quick method helps you maintain a clean, organized Gmail account—without any daily manual effort.
Step 1: Define Your Deletion Criteria
- Decide what counts as “old” or “unwanted.” For instance, you might target emails older than 30 days labeled as promotions.
- In Gmail, note down the specific search query you’d use (e.g.,
label:promotions older_than:30d
).
Tip: You can test your search query in Gmail first to see what results come up before implementing the script.
Step 2: Open the Script Editor
- In a new or existing Google Sheet, go to Extensions in the top menu.
- Select Apps Script to open the Script Editor.
- Alternatively, visit script.google.com directly to create a new standalone script.
Step 3: Add the Cleanup Code
Replace the searchQuery
in the script below with your desired criteria:
function cleanUpOldEmails() {
// Edit this query to match your cleanup criteria
var searchQuery = 'label:promotions older_than:30d';
// Get threads based on the query (limit the batch size to avoid timeouts)
var threads = GmailApp.search(searchQuery, 0, 100);
for (var i = 0; i < threads.length; i++) {
// Move threads to trash (you could also archive instead)
threads[i].moveToTrash();
}
Logger.log("Clean-up complete! " + threads.length + " threads moved to Trash.");
}
Explanation
searchQuery
: Defines which emails to find (e.g., older than 30 days with a certain label).GmailApp.search(...)
: Finds email threads matching your search query. The 0, 100
parameters limit the query to the first 100 results for safety.moveToTrash()
: Sends matched threads to the trash. You could replace this with archive()
or moveToArchive()
if you prefer archiving instead.
Step 4: Automate the Cleanup with a Trigger
- In the Script Editor, click the Triggers icon (clock symbol) on the left.
- Choose Add Trigger.
- Select the function
cleanUpOldEmails
. - Under “Select event source,” pick Time-driven.
- Choose a schedule (e.g., once per day).
- Click Save and authorize the script if prompted.
Conclusion
With this simple Apps Script, your Gmail inbox will automatically clean itself of old or unwanted messages on a routine basis. Whether you’re looking to free up space, stay under storage limits, or just keep your inbox tidy, automated email cleanups are a quick win for productivity.
Need more advanced automations? Contact us to learn how we can streamline your entire Google Workspace experience—from Gmail to Drive and beyond!