Gmail – How to Automatically Empty Gmail Trash Using Google Apps Script

gmailgoogle-apps-script

I found this post on how to do the above but it doesn't appear to work?

Here is the error message

Nov 25, 2020, 3:52:51 PM    Error   GoogleJsonResponseException: API call to gmail.users.threads.delete failed with error: Delegation denied for anstissr@gmail.com
    at [unknown function](Code:29:33)
    at removeMyTest2(Code:23:28)

Go to https://script.google.com

Then create a new project and paste the below into it:

function removeMyTest2() {

var mymail = "email@gmail.com";

var mylabel = "trash";

var permanentlyRemoveMyLabel = true;

var pageToken;

do {

    var threadList = Gmail.Users.Threads.list('me', {

    q: 'in:' + mylabel,

    pageToken: pageToken

    });

    if (threadList.threads && threadList.threads.length > 0) {

        threadList.threads.forEach(function(thread) {

        Logger.log('id: %s snippet: %s', thread.id, thread.snippet);

        if (permanentlyRemoveMyLabel) {

            Gmail.Users.Threads.remove(mymail, thread.id);

            Logger.log('id: %s snippet: %s REMOVED', thread.id, thread.snippet);

        }

    });

   }

   pageToken = threadList.nextPageToken;

   } while (pageToken);

}

If you try and run the script as is it will error out.

Next you click on Resources and go to Advanced Google Services.

Scroll down to Gmail API and turn that on.

Next click Google Cloud Platform Link on that same window that came up
where you enabled the Gmail API.

Then click on the Enable services and API and search for Gmail. Click
on Gmail and then enable it.

Then go back to your script screen and click on the menu Edit and go
to Current project's triggers.

Set a trigger to run the script either every minute/hour or whatever
time interval that you want the script to run and empty your trash.

Keep in mind you can delete from IN:TRASH IN:SPAM or whatever other
label you want. It won't delete reminders and the deletion is final.
You can't recover any of the emails.

Best Answer

Warning

The code from the referred answer deletes permanently the messages from the Gmail Trash. We should not copy and execute code that we don't understand.


It's very likely that the referred error message occured because the following code line was not edited:

var mymail = "email@gmail.com";

Replace "email@gmail.com" by Session.getActiveUser().getEmail()

Resource


The original content of the referred answer was obsolete. It was edited by me few moments ago.