Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Google Apps Script script to bulk delete large amounts of email in Gmail while avoiding the error #793 which Gmail encounters normally
/*
This script, when used with Google Apps Scripts will delete 400 emails and
can be triggered to run every few minutes without user interaction enabling you
to bulk delete email in Gmail without getting the #793 error from Gmail.
Google returns a maximum of 500 threads. This limits to 400 threads in case 500
threads is causing timeouts
Configure the search query in the code below to match the type of emails
you want to delete
Browser to https://script.google.com/.
Start a script and paste in the code below.
After you past it in, save it and click the little clock looking button.
This is for your triggers. You can set up how frequently you want the script
to run (I did mine for every minute but others are seeing execution take longer than
a minute in which case you may want to run every 5 or 15 minutes).
This writeup from @timur-tabi goes into more detail : https://docs.google.com/document/d/1PLfAnNus-B87gHS1pkbmzFTkWckAPNcqmvO7hFo_gBc/edit
Source : # https://productforums.google.com/d/msg/gmail/YeQVDuPIQzA/kpZPDDj8TXkJ
*/
function batchDeleteEmail() {
var batchSize = 100 // Process up to 100 threads at once
var searchSize = 400 // Limit search result to a max of 400 threads. Use this if you encounter the "Exceeded maximum execution time" error
var threads = GmailApp.search('label:inbox from:user@example.com', 0, searchSize);
for (j = 0; j < threads.length; j+=batchSize) {
GmailApp.moveThreadsToTrash(threads.slice(j, j+batchSize));
}
}
@alex9jk
Copy link

alex9jk commented May 20, 2020

Works perfect! Thank you!

@oshrishaul
Copy link

oshrishaul commented Jun 14, 2020

Great solution!
Does anyone knows how to use the GmailApp.search to search for the following 2 conditions together:

  • all mails including all labels. should give the same results like "All Mail" label at the GUI
  • before x date

@Kbshopper28
Copy link

Kbshopper28 commented Oct 1, 2020

@fancywriter
Copy link

fancywriter commented Nov 16, 2020

An attempt to run this script gave me "Gmail operation not allowed. " error from google. 😕
On line GmailApp.search(...).

@avramovic
Copy link

avramovic commented Nov 27, 2020

@fancywriter Disable your popup blocker and allow the script to access your email, it worked for me and works flawlessly, except I had to put it to run every 5 minutes cause GMail was timing out when set to run every minute. Each time it's executed it runs for about 2-3 minutes and deletes up to 500 threads, so it should be done by the morning (in my case)

@timur-tabi
Copy link

timur-tabi commented Jan 4, 2021

When I try to implement this script, I was prompted to log into my Gmail account. At that point, I got this pop-up message:

This app is blocked

This app tried to access sensitive info in your Google Account. To keep your account safe, Google blocked this access.

How do I get around this?

Update: I wrote up instructions to get around this issue: https://docs.google.com/document/d/1PLfAnNus-B87gHS1pkbmzFTkWckAPNcqmvO7hFo_gBc/

@sharan779
Copy link

sharan779 commented Jan 26, 2021

This is great. thanks much!

@DestinyChan281
Copy link

DestinyChan281 commented Feb 23, 2021

hello, im trying to figure this out
i wanna delete emails from my social inbox but im having trouble figuring out how to set up this code

@gene1wood
Copy link
Author

gene1wood commented Feb 23, 2021

@DestinyChan281 Follow the instructions in the comments of the code above and share what step you're getting stuck at and what problem you're encountering.

@DestinyChan281
Copy link

DestinyChan281 commented Feb 24, 2021

nevermin, I think I figured it out
though i did get this error message alot
"Exception: Service invoked too many times for one day: gmail.
batchDeleteEmail @ Code.gs:19"

@gene1wood
Copy link
Author

gene1wood commented Feb 24, 2021

Service invoked too many times for one day

Sounds like Google is ratelimiting calls to the moveThreadsToTrash endpoint (or the search endpoint)

@DestinyChan281
Copy link

DestinyChan281 commented Feb 24, 2021

oh okay.
I guess I’ll just keep coming back to the script each day to reset the rate limit

@newboydj169
Copy link

newboydj169 commented Apr 6, 2021

really a nice feature, thank you so much.

@Kilarisowjanya
Copy link

Kilarisowjanya commented Apr 6, 2021

I want to delete mails from Social Label and done the steps mentioned in the comments exactly but It's not deleting my mails but the code is running successfully. I can see the triggers are happening at every 1 minute interval.
Kindly help me if anyone have any idea on it.
Thank you

@acechase
Copy link

acechase commented Aug 2, 2021

This is a great script! Thank you so much!!

Playing around a bit, I'm seeing timeouts occurring pretty regularly by the third or fourth batch. I'm also seeing each batch take a full minute to run so I pulled back the trigger interval to be once every 5 minutes rather than every 1 minute. I imagine it could cause odd behavior to have the same script running in parallel multiple times.

For anyone who's just cut & pasting and wants to see logging info, here's my full script with debug output:

function batchDeleteEmail() {
  var batchSize = 100 // Process up to 100 threads at once
  var threads = GmailApp.search('category:promotions older_than:3m');
  console.log('batch size is: ' + threads.length);
  for (j = 0; j < threads.length; j+=batchSize) {
    console.log('removing batch: ' + j);
    GmailApp.moveThreadsToTrash(threads.slice(j, j+batchSize));
  }
}

You can see the before after on how long each script run was taking when they were running in parallel:
Screen Shot 2021-08-02 at 9 08 35 AM

Since it's now finishing much more quickly, rather than increasingly the trigger interval back to 1m, the ideal scenario would be to increase the query size coming back from GmailApp.search. Unfortunately, Google caps that at 500 results per query.

@acechase
Copy link

acechase commented Aug 5, 2021

Screen Shot 2021-08-05 at 8 51 47 AM

LOL. Come on, Google! I've deleted about 70k of 160k promotion emails so far. So I'm on track to clear out that folder over the course of ~7 days.

@asifiqbal
Copy link

asifiqbal commented Aug 8, 2021

@timur-tabi
Copy link

timur-tabi commented Aug 8, 2021

Try this version. It limits to 400 threads:

function batchDeleteEmail() 
{
  // moveThreadsToTrash() only allows up to 100 threads at once
  var batchSize = 100

  // returns no more than 500 results, but that takes longer than
  // six minutes, so return less.  We don't want timeouts.
  var threads = GmailApp.search('label:inbox from:user@example.com', 0, 400);
  
  for (j = 0; j < threads.length; j += batchSize) {
    GmailApp.moveThreadsToTrash(threads.slice(j, j + batchSize));
  }
}

I suggest running this script not more often than once per hour.

@asifiqbal
Copy link

asifiqbal commented Aug 8, 2021

Try this version. It limits to 400 threads:

function batchDeleteEmail() 
{
  // moveThreadsToTrash() only allows up to 100 threads at once
  var batchSize = 100

  // returns no more than 500 results, but that takes longer than
  // six minutes, so return less.  We don't want timeouts.
  var threads = GmailApp.search('label:inbox from:user@example.com', 0, 400);
  
  for (j = 0; j < threads.length; j += batchSize) {
    GmailApp.moveThreadsToTrash(threads.slice(j, j + batchSize));
  }
}

I suggest running this script not more often than once per hour.

That worked perfect. Now I just setup a trigger to run hourly. Does it start at the beginning of the hour? There is nothing under Last run yet
Screen Shot 2021-08-08 at 6 09 49 PM

@asifiqbal
Copy link

asifiqbal commented Aug 8, 2021

Try this version. It limits to 400 threads:

function batchDeleteEmail() 
{
  // moveThreadsToTrash() only allows up to 100 threads at once
  var batchSize = 100

  // returns no more than 500 results, but that takes longer than
  // six minutes, so return less.  We don't want timeouts.
  var threads = GmailApp.search('label:inbox from:user@example.com', 0, 400);
  
  for (j = 0; j < threads.length; j += batchSize) {
    GmailApp.moveThreadsToTrash(threads.slice(j, j + batchSize));
  }
}

I suggest running this script not more often than once per hour.

That worked perfect. Now I just setup a trigger to run hourly. Does it start at the beginning of the hour? There is nothing under Last run yet
Screen Shot 2021-08-08 at 6 09 49 PM

I changed it to run every 15 mins and I do see it running. I will change it back to run it every hour. Thanks!

@gene1wood
Copy link
Author

gene1wood commented Aug 8, 2021

@timur-tabi Thank you, I've added your suggestion to the gist above and linked to your Google Doc.

@asifiqbal
Copy link

asifiqbal commented Aug 19, 2021

So the script has been working fine for most times (trigger is setup for one per hr) with searchSize = 400. However I still get the Exceeded maximum execution time once in a while and sometimes says Exception: Gmail operation not allowed. Out of 24 a day (one/hr) I get 3 failed with gmail operation not allowed and 3 timedout with execeeded max execution time. 75% success rate (yikes). Google GMAIL api is pretty unstable seems like.

@ginoliang1130
Copy link

ginoliang1130 commented Aug 30, 2021

Thank you. This script is very helpful to me. I release a new version to everyone. By the way, I added Mandarin in the comments. Hope it helps others.

function batchDeleteEmail() {
  var batchSize = 100 // Process up to 100 threads at once
  // 如果需要時間可以加上 [older_than:00m、00d、00h],[category:] 可換成 [label:]
  // If you need to add time conditions, you can use d(day) and h(hours) instead.
  // [category:] can be replace [label:].
  var threads = GmailApp.search('category:forums');
  console.log('batch size is: ' + threads.length);
  for (j = 0; j < threads.length; j+=batchSize) {
    console.log('removing batch: ' + j);
    GmailApp.moveThreadsToTrash(threads.slice(j, j+batchSize));
  }
}

@aalemayhu
Copy link

aalemayhu commented Nov 6, 2021

Thank you so much! For anyone else wanting to delete patches, this is my

function batchDeleteEmail() {
  var batchSize = 100 // Process up to 100 threads at once
  var searchSize = 400 // Limit search result to a max of 400 threads. Use this if you encounter the "Exceeded maximum execution time" error
  
  var threads = GmailApp.search('subject: PATCH', 0, searchSize);
  for (j = 0; j < threads.length; j+=batchSize) {
    GmailApp.moveThreadsToTrash(threads.slice(j, j+batchSize));
  }
}

@birajblg1987
Copy link

birajblg1987 commented Apr 24, 2022

How to add multiple email addresses to the list?

@Hectorhammett
Copy link

Hectorhammett commented Apr 25, 2022

I have an issue and I can't debug it. Is it me or the docs are a little bit stingy? Anyways, I cannot run the script as it says
Exception: Gmail Operation not allowed
On the line using GmailApp.search. Oddly enough, I left it running for something like an hour and it was working but then it stopped working. It sounds like a limit hit? but I am unsure as I am getting a Gmail operation not allowed and not something like limit error or something else. Any possible ideas?

Thank you!

@gene1wood
Copy link
Author

gene1wood commented Apr 25, 2022

How to add multiple email addresses to the list?

@birajblg1987 You can customize the GMail search terms on line 27 in any way you wish, including adding additional email addresses.

@gene1wood
Copy link
Author

gene1wood commented Apr 25, 2022

@Hectorhammett Indeed, @asifiqbal also mentions above encountering that limit.

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