A Ruby script that automatically cleans up old emails from your Gmail account by deleting messages older than specified thresholds across different categories.
- Category-based cleanup: Handles Forums, Purchases, Social, Updates, Promotions, and all old emails
- OAuth 2.0 authentication: Secure Google API authentication with token storage
- Batch processing: Efficiently processes emails in batches of 500
- Configurable thresholds: Different retention periods for different email categories
- Ruby (check
.ruby-versionfor version) - Gmail account with API access
- Google Cloud Platform project with Gmail API enabled
-
Clone the repository
git clone <repository-url> cd gmail-cleaner
-
Install dependencies
bundle install
-
Set up Google Cloud Platform
- Go to Google Cloud Console
- Create a new project
- Enable the Gmail API
- Create OAuth 2.0 credentials:
- Application type: Desktop app
- Download the
client_secret.jsonfile
- Place
client_secret.jsonin the project root
The script uses these scopes:
https://www.googleapis.com/auth/gmail.modify- Read, send, delete, and manage emailhttps://mail.google.com/- Full access to the account
| Category | Retention |
|---|---|
| Forums | 3 months |
| Purchases | 6 months |
| Social | 3 months |
| Updates | 6 months |
| Promotions | 3 months |
| All other emails | 10 years |
Modify the queries array in app.rb to adjust these thresholds.
-
Run the script
ruby app.rb
-
First-time authorization
- A local OAuth server starts on
http://localhost:8888 - Your default browser opens to Google's login page
- After authorizing, tokens are saved to
token.json - Subsequent runs use cached credentials
- A local OAuth server starts on
-
Monitor progress
- The script displays each query being processed
- Shows batch deletion progress
- Reports total emails deleted
| File | Description |
|---|---|
app.rb |
Main Ruby script |
Gemfile |
Ruby dependencies |
client_secret.json |
Google OAuth credentials (you provide) |
token.json |
Cached OAuth tokens (auto-generated) |
Important: Never commit client_secret.json or token.json to version control!
This project includes a .gitignore that excludes:
client_secret.json- Your OAuth client secrettoken.json- Cached authentication tokens.DS_Store- macOS system files
If you accidentally commit these files, revoke them immediately in Google Cloud Console and create new credentials.
- Ensure the OAuth redirect URI matches your Google Cloud Console configuration
- Delete
token.jsonand re-run the script to re-authenticate
- Run
ruby app.rbto trigger the OAuth flow
- The script processes in batches with minimal delay
- For very large mailboxes, consider running during off-peak hours
MIT License