leponceau.org

Programming And Stuff, You Know The Thing…

Google Mail Apps Script: Don't Send Mails From Your Contacts To The GMail Spam Folder

Posted at — May 30, 2018

There seems to be no way to trigger a Google Apps Script upon arrival of a new mail. Instead, you can let Google run the following script every hour to take such emails out of the spam folder.

The script simply checks the From: header of new mails in your spam folder and tries to find the email addresses found there in your Google Contacts. If it finds a contact there, the entire thread will be moved to your inbox. We don’t actually prevent messages from going to the Google Mail spam folder, instead we simply move them back to the inbox. This won’t work for old emails that have been put into the spam folder before activating the script because the script will always limit its scope to emails received since its last run minus some margin.

function unspam() {
  var userProperties = PropertiesService.getUserProperties();
  //userProperties.deleteAllProperties();
  var lastRun = userProperties.getProperty('LAST_RUN');
  var date = new Date();
  Logger.log("date: " + date);
  var dateSecs = Math.floor(date.valueOf()/1000);
  if (lastRun == null) {
    lastRun = dateSecs;
    Logger.log("lastRun was null");
  }
  Logger.log("lastRun = " + new Date(lastRun*1000));
  var timeFrom = lastRun - 300;
  var nMoved = 0;
  
  var threads = GmailApp.search('in:spam after:' + timeFrom);
  Logger.log("spam threads found: " + threads.length);
  for (var i = 0; i < threads.length; i++) {
    Logger.log("thread: " + threads[i].getFirstMessageSubject());
    var msgs = threads[i].getMessages();
    var found = false;
    for (var j = 0; j < msgs.length && !found; j++) {
      var from = parseEmailHeader(msgs[j]);
      Logger.log("from: " + from);
      if (ContactsApp.getContact(from) != null) {
        found = true;
        Logger.log("address found in contacts");
      }
    }
    if (found) {
      Logger.log("moving to inbox");
      threads[i].moveToInbox();
      nMoved++;
    }
  }
  
  Logger.log("threads moved to inbox: " + nMoved);
  userProperties.setProperty('LAST_RUN', dateSecs);
  Logger.log("new lastRun = " + new Date(dateSecs*1000));
}

function parseEmailHeader(message) {
  
  var header = message.getFrom();
  if (header == null) return null;
  header = header.trim();

  var email = null;
  
  var emails = header.match(/[^@<\s]+@[^@\s>]+/g);
  
  if (emails) {
    email = emails[0];
  }
  
  return email;
}

Use at your own risk only!

The current and most recent sources can be found here. Just select File->create copy, and set up a timed trigger for the execution of the unspam() method. Run it once manually to grant access, a second time to verify that it is running. You can check logs inside Google’s apps script editor after manual execution. Don’t forget to visit Google’s Apps Script console where your script project will end up.