Sitemap

Automating Gmail Deletion with Go

3 min readFeb 10, 2025

Managing an overflowing inbox can be challenging, especially when old emails pile up over the years. Fortunately, with the Gmail API and Go, we can automate the deletion of emails older than a specified period. In this article, we will walk through a Go-based solution to delete emails older than five years automatically.

Prerequisites

Before we start coding, ensure you have the following:

  • A Google Cloud project with Gmail API enabled
  • OAuth 2.0 credentials (JSON file)
  • Go installed on your machine
  • Gmail API client library for Go

Setting Up OAuth2 Authentication

Gmail API requires OAuth2 authentication. You need to obtain OAuth credentials by following these steps:

  1. Visit the Google Cloud Console
  2. Create a new project and enable the Gmail API
  3. Generate OAuth 2.0 credentials and download the credentials.json file
  4. Store the credentials.json file in your project's root directory

Implementing the Gmail Cleanup Tool

The following Go program will authenticate with Gmail, retrieve emails older than five years, and delete them.

package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/gmail/v1"
)
const (
credentialFile = "credentials.json"
tokenFile = "token.json"
)
func main() {
ctx := context.Background()
b, err := os.ReadFile(credentialFile)
if err != nil {
log.Fatalf("Unable to read credentials file: %v", err)
}
config, err := google.ConfigFromJSON(b, "https://mail.google.com/")
if err != nil {
log.Fatalf("Unable to parse credentials file: %v", err)
}
config.RedirectURL = "http://localhost:8080/oauth2callback" tok, err := tokenFromFile(tokenFile)
if err != nil {
tok = getTokenFromWeb(config)
saveToken(tokenFile, tok)
}
client := config.Client(ctx, tok) gmailService, err := gmail.New(client)
if err != nil {
log.Fatalf("Unable to create Gmail client: %v", err)
}
query := "older_than:5y"
user := "me"
var messages []*gmail.Message
err = gmailService.Users.Messages.List(user).Q(query).Pages(ctx, func(resp *gmail.ListMessagesResponse) error {
messages = append(messages, resp.Messages...)
return nil
})
if err != nil {
log.Fatalf("Unable to retrieve messages: %v", err)
}
fmt.Printf("Found %d messages to delete.\n", len(messages)) for _, msg := range messages {
err = gmailService.Users.Messages.Delete(user, msg.Id).Do()
if err != nil {
log.Printf("Failed to delete message (ID: %s): %v", msg.Id, err)
} else {
fmt.Printf("Deleted message (ID: %s)\n", msg.Id)
time.Sleep(100 * time.Millisecond)
}
}
fmt.Println("Deletion process completed.")
}

Explanation of the Code

OAuth Authentication:

  • Reads OAuth credentials from credentials.json.
  • Checks if an access token exists; if not, it initiates the authentication flow.
  • Saves the token for future use.

Connecting to Gmail API:

  • Establishes a connection using the authenticated client.

Retrieving Emails:

  • Uses a query (older_than:5y) to find emails older than five years.
  • Implements pagination to fetch all matching emails.

Deleting Emails:

  • Iterates through the retrieved emails and deletes them using the Gmail API.
  • Introduces a short delay to avoid rate limits.

Running the Script

  1. Download the credentials.json file from Google Cloud.
  2. Run the script: go run main.go
  3. Authenticate via the provided URL and grant permission.
  4. The script will delete all emails older than five years.

Security Considerations

  • Ensure credentials.json and token.json are stored securely and not exposed.
  • Use environment variables or a secret manager for storing sensitive data.
  • Implement proper logging and error handling in production.

Conclusion

This script provides an automated way to clean up old emails from Gmail using Go. It helps manage inbox clutter and ensures that obsolete messages do not accumulate over time. You can further enhance it by adding filters, logging, or scheduling it as a cron job for periodic cleanup.

Happy coding!

Feel free to reach out to me on LinkedIn, which you can find below. Looking forward to connecting!

https://www.linkedin.com/in/tomoharu-tsutsumi/

--

--

Tomoharu Tsutsumi
Tomoharu Tsutsumi

Written by Tomoharu Tsutsumi

Senior SWE (Ruby, Go, TypeScript, JavaScript) in Vancouver

No responses yet