javascriptemailautomationgmail

Automatically delete emails from gmail account spam folder which contain specific keywords


For the past year or two I was unsure how to delete permanently, skipping the trash and had to make do with a subpar solution. I now have a method to delete spam messages which match certain phrases permanently. Please add any phrases you want to filter for into the 'phrases' array. You will also need to add the Gmail service to your Google Scripts project. Finally, if you want to automate this you will need to go the triggers tab and add a timed (or other trigger type of your choosing) trigger to your project. I run mine for example every 5 minutes right now. The first time you attempt to run this you will need to tell Google to allow it to run since your project isn't verified by Google, it will list the accesses being requested and then you can choose to accept/provide access. You may also be asked specifically for access to your Gmail account. Good luck!


// Remember to add the Gmail service to your google scripts project or you will get errors. This can be done by clicking the '+' next to "Services"

function deleteSpamEmails() {
  var userEmail = Session.getActiveUser().getEmail(); // Get the current user's email address
  
  // Define the phrases or words to search for in the subject or body, lowercase
  var phrases = ["hawaiian escapes","yorktown real estate","cheap vitamins @ vita-shack"];
  
  // Get emails/threads in the Spam folder
  var threads = GmailApp.search("label:Spam"); // The label we will delete from
  
  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages(); // Get allof the messages in the thread
    
    for (var j = 0; j < messages.length; j++) {
      //Get subject and body in lowercase for easier comparison
      var subject = messages[j].getSubject().toLowerCase(); // Convert subject to lowercase
      var body = messages[j].getBody().toLowerCase(); // Convert body to lowercase
      
      // Check if any of the phrases in the array above are included in the subject or body of the email
      var shouldDelete = phrases.some(function(phrase) {
        return subject.includes(phrase.toLowerCase()) || body.includes(phrase.toLowerCase());
      });
      
      if (shouldDelete) {
        var messageId = messages[j].getId(); // Get the ID of the message
        
        // Use the Gmail API to delete the message permanently, skipping the trash
        var url = "https://www.googleapis.com/gmail/v1/users/" + userEmail + "/messages/" + messageId;
        var options = {
          method: "DELETE",
          headers: {
            Authorization: "Bearer " + ScriptApp.getOAuthToken() // Use the OAuth token for authentication (remember to authorize google scripts to use your email)
          }
        };
        
        UrlFetchApp.fetch(url, options); // Send the api request to delete the message
      }
    }
  }
}
deleteSpamEmails();

Resources: Gmail apps script API


Solution

  • I was able to run the script with a few changes:

        function deleteForevers(userId='me') {
      var threads = GmailApp.search("in:spam");
    
      for (var i = 0; i < threads.length; i++) {
        var msg = threads[i].getMessages()[0];
        if (msg.getPlainBody().match(/prizes|miracle|darling|(real estate)|(nigerian prince)/gi) !== null){
            Gmail.Users.Threads.remove(userId='me', threads[i].getId().toString());
        }
      }
    }
    deleteForevers("[your_email_here@gmail.com]")
    

    Note: before using the script, you need to enable the advanced service [GmailApi] (from Google Guide)