A simple yet effective Google Apps Script to keep your Gmail inbox clean and organized by automatically removing unwanted emails based on customizable criteria.
- Automatically removes emails based on Gmail search queries
- Configurable for different categories, labels, and time criteria
- Respects starred emails
- Batch processing to handle large volumes of email
- Detailed logging of operations
By default, the script is configured to remove:
- Emails in the "Promotions" category
- That are in the inbox
- That are NOT starred
- That are older than 1 year
- Open Google Apps Script
- Create a new project
- Copy and paste the code from the
gmail-cleanup.jsfile - Save the project with a descriptive name (e.g., "Gmail Cleanup")
- Open your Google Apps Script project
- Select the
runCleanupfunction from the dropdown menu - Click the play button (
▶️ ) to run the script - First time, you'll need to authorize the script to access your Gmail
- In your Google Apps Script project, click on the clock icon in the sidebar (⏰)
- Click "Add Trigger"
- Configure the trigger:
- Select the
cleanupfunction - Choose event source as "Time-driven"
- Select desired frequency (daily, weekly, etc.)
- Configure specific time for execution
- Select the
- Save the trigger
Edit the queryArray to include your own search queries. Google Apps Script uses the same search syntax as Gmail.
Useful query examples:
const queryArray = [
"category:promotions in:inbox AND -in:starred older_than:", // Old promotions
"category:social in:inbox AND -in:starred older_than:", // Old social
"label:newsletter older_than:", // Old newsletters
"from:example.com AND -in:starred older_than:", // Old emails from a specific domain
];Edit the delayInfo array to change the time period for each query:
const delayInfo = [
{index: 0, type: "year", value: 1}, // 1 year for query at position 0
{index: 1, type: "month", value: 6}, // 6 months for query at position 1
{index: 2, type: "day", value: 30}, // 30 days for query at position 2
{index: 3, type: "month", value: 3} // 3 months for query at position 3
];- Test First: Before scheduling automatic runs, execute the script manually to verify it works as expected.
- Backups: Consider backing up important emails.
- Trash: Emails are moved to trash, not immediately permanently deleted.
MIT — © 2026 Ranuk IT Solutions | ranuk.dev
Contributions are welcome. Feel free to open an issue or submit a pull request.