GAS: Automating Email Organization in Gmail with Google Apps Script for Frequent Senders

Contents

Overview

“Streamline Your Gmail: Auto-label Emails from Frequent Senders using Google Apps Script”
Discover a script that helps you sift through the mountain of emails and locate the information you need promptly.

Explanation and Purpose

Have you ever felt the need to manage emails from specific senders more efficiently amidst receiving a plethora of emails daily for your tasks? This script caters to such needs by automatically labeling emails coming from domains that contact you frequently.

Step-by-step Guide

  1. Open Google Drive
    Click the ‘+ New’ button located in the upper left of the Google Drive screen and select ‘Google Apps Script’ from ‘More’.
  2. Access Script Editor
    Paste the script in the new tab that opens with the Script Editor.
  3. Save and Run the Script
    Click the save icon at the top of the editor and then click the triangle run button.
  4. Set up a Trigger
    Click the clock icon on the left to add a new trigger and configure the frequency with which this script should run.

Explanation of the Code

This script scans the emails in your Gmail inbox and counts the emails based on the sender’s domain. It then automatically creates and applies labels to domains from which a certain number of emails have been received.

Safety Considerations

This script only extracts the domain information of the senders without reading the content of the emails. However, permissions will be requested when utilizing triggers and Apps Script. Please refer to Google’s official documentation for detailed information on security.

Sample Script

function labelFrequentSenders() {
  var threads = GmailApp.getInboxThreads();
  var sendersCount = {};
  
  threads.forEach(function(thread) {
    var messages = thread.getMessages();
    
    messages.forEach(function(message) {
      var fromAddress = message.getFrom();
      var domain = fromAddress.split('@')[1];
      
      // Count the number of sender emails
      sendersCount[domain] = (sendersCount[domain] || 0) + 1;
    });
  });
  
  // Apply labels only to senders with more than a certain number of emails
  var threshold = 5; // This is an example, please set the actual threshold
  
  for(var domain in sendersCount) {
    if(sendersCount[domain] >= threshold) {
      var label = GmailApp.getUserLabelByName(domain);
      
      if(!label) {
        label = GmailApp.createLabel(domain);
      }
      
      // Apply label to target thread
      GmailApp.search('from:@' + domain).forEach(function(thread) {
        thread.addLabel(label);
      });
    }
  }
}

Thank you