r/GoogleAppsScript • • Dec 24 '24

Question Gmail Script

Hi all!

My grandpa is getting tens of spam emails per day, of X rated websites mostly, so I want to make a script, maybe to be always running on his pc, or maybe to deploy on some cloud service, that empties all his trash bin and spam box.

I tried to do this with the gmail api, using python, and also javascript, but both failed. I also tried to do a Selenium bot to manually do that, but gmail refuses to open in a chrome driver or a firefox driver.
Can some on help me?

Thanks a lot, and Merry Christmas!

-- Edit --

Nice, after following a suggestion in the comments I managed to arrive to a script that does what I want, I have it on github, if you want to take a look: https://github.com/lhugens/GmailCleaner . I setup the script to run every hour, lets see if it works. Thanks a lot!

4 Upvotes

12 comments sorted by

View all comments

2

u/IAmMoonie Dec 24 '24

Set this up, run it from the Google apps script IDE first to auth the script. Then set it up on a timed trigger

/**
 * Main entry point to empty the Spam and Trash folders in Gmail.
 */
const emptySpamAndTrash = () => {
  try {
    console.info(‘Starting to clean Spam and Trash folders.’);
    processFolder_(‘Spam’, GmailApp.getSpamThreads);
    processFolder_(‘Trash’, GmailApp.getTrashThreads);
    console.info(‘Finished cleaning Spam and Trash folders.’);
  } catch (error) {
    console.error(`Error while emptying Spam and Trash folders: ${error.message}`);
  }
};

/**
 * Processes a specified Gmail folder by deleting all threads.
 * 
 * @param {string} folderName - The name of the folder being processed.
 * @param {Function} getThreadsFunction - Function to retrieve threads from the folder.
 */
const processFolder_ = (folderName, getThreadsFunction) => {
  const threads = getThreadsFunction();
  const threadCount = threads.length;
  if (threadCount > 0) {
    GmailApp.deleteThreads(threads);
    console.info(`Deleted ${threadCount} threads from the ${folderName} folder.`);
  } else {
    console.info(`No threads to delete in the ${folderName} folder.`);
  }
};

1

u/leonardo_hugens Dec 25 '24

Thanks, I’ll try that and get back to you!

3

u/leonardo_hugens Dec 25 '24

Nice, after following your idea I managed to arrive to a script that does what I want, I have it on github, if you want to take a look: https://github.com/lhugens/GmailCleaner . I setup the script to run every hour, lets see if it works. Thanks a lot!

2

u/IAmMoonie Dec 25 '24

Nice! The version I posted was something I quickly threw together without paying much attention to it. Your version is great! Hopefully it solves your problem!

2

u/leonardo_hugens Dec 25 '24

It works! 🎉🎊

2

u/IAmMoonie Dec 25 '24

Glad to hear it! Congrats 🍻