Gmail – Auto-create and auto-apply labels to emails depending on sender’s email address

gmailgmail-filtersgmail-labels

How to auto-create and auto-apply labels to emails depending on the sender email address?

Example: Once I receive an email from no-reply@amazon.ca, Gmail will automatically create a new label "amazon.ca" and auto-apply "amazon.ca" to this message.

Please don't confuse with manual filters. I am talking about Gmail creating labels for me automatically.

Best Answer

Here is a script that does this. Set a trigger to run it every 5 minutes (the interval can be changed, but then you should change the variable interval accordingly).

It gets the recent threads in inbox. Only the threads with one message are considered, to avoid labeling based on replies, etc.

Also, if some of your messages skip inbox but you still want to auto-label them, remove is:inbox part from the line var threads = GmailApp.search(....

function autoLabel() {
  var interval = 5;    //  if the script runs every 5 minutes; change otherwise
  var timeFrom = Math.floor(Date.now()/1000) - 60 * interval;
  var threads = GmailApp.search('is:inbox after:' + timeFrom);
  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    if (messages.length == 1) {      // only deal with threads with one message
      var labels = threads[i].getLabels();
      var domain = messages[0].getFrom().match(/@([^>]+)/)[1];
      var label = GmailApp.getUserLabelByName(domain);
      if (!label) {
        var label = GmailApp.createLabel(domain);
      }
      if (labels.indexOf(label) == -1) {
        threads[i].addLabel(label);
      }
    }
  }
}