2

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.

  • You are right corrected, sender – monstro Mar 19 '16 at 8:13
1

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);
      }
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.