Skip to content

Instantly share code, notes, and snippets.

@evgeniidatsiuk
Last active April 18, 2024 10:39
Show Gist options
  • Save evgeniidatsiuk/d2061f07f05d65959ec8916df05a649f to your computer and use it in GitHub Desktop.
Save evgeniidatsiuk/d2061f07f05d65959ec8916df05a649f to your computer and use it in GitHub Desktop.
Automate Gmail Cleanup: Delete Old Emails Using Google Apps Script and JavaScript // How to remove all emails from gmail // Gmail: delete old emails automatically // Automatically deletes old emails that match the specified label.

How to Remove Old Emails from Gmail Automatically

Step 1: Login and Create a Project on Google Apps Script

Go to https://script.google.com/ and sign in with your Google account. Then, create a new project.

Step 2: Run the Script

Copy and paste the following script into your Google Apps Script editor:

function deleteOldEmails() { 
  const threads = GmailApp.search('older_than:1d');
  for (let i = 0; i < threads.length; i++) {
    threads[i].moveToTrash();
  }
}

deleteOldEmails();

This script will delete emails older than 1 day. Adjust the older_than parameter to fit your needs.

Step 3: Rerun the Script Using the Console

Due to script execution time limits (5 minutes), you may need to rerun the script manually. You can do this using the browser console:

// Select the element to monitor for changes in the disabled property
const elementToMonitor = document.querySelector('button[aria-label="Запустити вибрану функцію"]');

// Create a MutationObserver instance
const observer = new MutationObserver((mutationsList, observer) => {
  for(const mutation of mutationsList) {
    // Check if the mutation is related to the 'disabled' property
    if (mutation.attributeName === 'disabled') {
      if (!mutation.target.hasAttribute('disabled')) {
        console.log('Triggered click');
        // Trigger a click event when disabled property is removed
        mutation.target.click();
      }
    }
  }
});

// Start observing the element for attribute changes
observer.observe(elementToMonitor, { attributes: true });

This script will automatically click the button to rerun the email deletion process when the disabled property is removed.


This guide provides a straightforward method to automate the cleanup of old emails in Gmail using Google Apps Script and JavaScript. Enjoy a clutter-free inbox!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment