📧 Automate Gmail Cleanup with Google Apps Script: Delete Old Emails Easily 🚀

📧 Automate Gmail Cleanup with Google Apps Script: Delete Old Emails Easily 🚀

Running out of Gmail storage? Here's a step-by-step guide to automate deleting emails older than 3 years using Google Apps Script — and configure it as a Web App! 💡

Step-by-Step Guide

1️⃣ Go to Google Apps Script:

2️⃣ Paste this code in the script editor:


function deleteOldEmails() {
  var maxThreadsPerLoop = 50; // Emails to process per iteration

  for (var count = 1; count <= 10; count++) { 
    Logger.log("Running loop number: " + count);

    var date = new Date();
    date.setFullYear(date.getFullYear() - 3); // Emails older than 3 years
    var formattedDate = Utilities.formatDate(date, "GMT", "yyyy/MM/dd");

    // Search for emails before the date
    var threads = GmailApp.search('before:' + formattedDate, 0, maxThreadsPerLoop);
    Logger.log("Found " + threads.length + " threads to delete.");

    // Move threads to Trash
    for (var i = 0; i < threads.length; i++) {
      threads[i].moveToTrash();
    }

    if (threads.length < maxThreadsPerLoop) {
      Logger.log("No more threads found. Stopping process.");
      break;
    }

    Utilities.sleep(2000); // Pause to avoid rate limits
  }
  Logger.log("Deletion process completed.");
}
        

3️⃣ Deploy the script as a Web App:

  • Go to "Implement" > New Deployment.
  • Select Web App as the type.
  • Set permissions:Execute as: Me (your email).Who has access: Only you, for security.

4️⃣ Authorize the script: Grant Gmail permissions when prompted.

5️⃣ Run the Script: Open the script, run it, and check the logs under "Execution Logs" to track progress.

Why Automate This?

Save Space: Automatically clean up emails older than 3 years.

Efficiency: Deletes emails in chunks of 50 to avoid rate limits.

No Manual Work: Set it and forget it!

Useful tip, this was life saving 🤗

To view or add a comment, sign in

More articles by Mario Brenes

Insights from the community

Others also viewed

Explore topics