1
votes

User is receiving a large volume of unwanted emails from a specific sender. Blocking moves the email to spam, while filtering moves the email to trash. Both of these still expose the user to the emails if those folders are checked.

What I'm looking for is a script that will permanently delete emails from the specified email address either when the emails are received, or on a frequent schedule.

I have almost no familiarity with google scripts or js, the best I have as relates to code is some rudimentary vba.

Researching this issue brought me to using google apps as a potential solution as gmail does not provide any automated way to permanently delete email. Below is some code I found googling around, although I can't get very far with it due to my total lack of apps script knowledge.

function DeleteEmailByLabel(e) {[email protected]}
var bannedLabel = 'BLOCKEDSENDER';
var deleteLabel = GmailApp.getUserLabelByName(bannedLabel);
if ( deleteLabel != null ) {[email protected]}
var threads = deleteLabel.getThreads();
for (var i = 0; i < threads.length; i++) {
Gmail.Users.Messages.remove('me', threads[i].getId());
}
} else {
deleteLabel = GmailApp.createLabel(bannedLabel);
}
}

I expect the above code to run and remove email from my test account, from the trash folder. However instead I get this error. This looks like basic syntax stuff but I'm out of my league here.

Missing ; before statement. (line 1, file "filename")

Thanks in advance.

1

1 Answers

1
votes

Before you could use this in the Apps Script, please note to do the following:

  1. Create a filter in the user's Gmail account such that a specific & unique label is allocated to such emails (you can "mark them as read" or "send them to spam"; it wouldn't matter)
  2. This function uses some of the advanced Gmail APIs and as such, require you to enable them from the script editor first, before running the script. To achieve this, go to:

Resources > Advanced Google Services... > Scroll all the way down to Gmail API > toggle the off button to on

Advanced resources

function deleteEmails() {
  var bannedLabel = 'BLOCKEDSENDER' // replace with the label name, as setup in filters
  var deleteLabel = GmailApp.getUserLabelByName(bannedLabel);  
  if ( deleteLabel != null ) {
    var threads = deleteLabel.getThreads();  
    for (var i=0; i<threads.length; i++) {
      Gmail.Users.Threads.remove('me', threads[i].getId());
    }    
  } else {
    // do something
  }
}