<img alt="Google Apps Script Projects to Supercharge Your Gmail Experience" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/Google-Apps-Script-Projects-to-Supercharge-Your-Gmail-Experience-800×420.jpg" data- decoding="async" height="420" src="data:image/svg xml,” width=”800″>

Once again, I am here to talk about productivity and automation in Gmail. This time around, we’re going full-on geek mode and will be using Google Apps Script to improve your Gmail experience.

Gmail has many built-in settings you can tweak to automate tasks and increase productivity. However, it has its limits and many features don’t offer enough customization options. This is where you can take matters into your own hands using Google Apps Script.

With it, you can create custom scripts that can perform tasks that Gmail natively can’t. Not only that, you can set time-based triggers to automate these scripts.

To get you started, I am listing some useful scripts that will surely enhance your Gmail experience. I have ensured that each script automatically solves common problems, such as duplicates or auto-creating a new folder. Therefore, some scripts might seem a bit longer than their intended purpose.

Create a Script in Google Apps Script

Before getting into applying and customizing these scripts, you need to know how to create a script in Google Apps Script and run it. Here’s how:

Open up Google Apps Script and click on the New project button in the left panel.

<img alt="google-apps-script-new-project" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/google-apps-script-new-project.jpg" data- decoding="async" height="355" src="data:image/svg xml,” width=”800″>

Here you need to remove all the code already written and copy/paste the script that I will provide. Afterward, click on the Save button to save the script.

<img alt="create-new-script" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/create-new-script.jpg" data- decoding="async" height="378" src="data:image/svg xml,” width=”800″>

To execute the script, click on the Run button right next to Save. You’ll be asked to give permissions and there will be a warning that the script isn’t verified. You can ignore the warning and give permissions since the script is for personal use and Google hasn’t reviewed it.

<img alt="not-verified-warning" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/not-verified-warning.jpg" data- decoding="async" height="376" src="data:image/svg xml,” width=”800″>

That’s it, the script will run and it will show in the execution log whether it has been successfully executed or not.

Set Up a Trigger

Many of these scripts work best when they are triggered automatically. Thankfully, Google Apps Script also has a section to create time-based triggers for each script so they execute automatically.

However, before I tell you about creating a trigger, you should know that Google Apps Script has limited quotas based on whether you are subscribed to the Google Workspace plan or not. If you have too many scripts running at a time and too frequently, then you may reach the daily quota which will stop the service for the time.

Even though you have the option to execute scripts every minute, it would be a huge drain on your daily quota. Make sure you only set a timer that gets the job done reliably.

To create a trigger, click on Triggers in the left panel while the script is open and then click on the Add Trigger button.

<img alt="add-trigger" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/add-trigger.jpg" data- decoding="async" height="370" src="data:image/svg xml,” width=”800″>

Here you can choose a timer in minutes to up to months and the interval. You can also select a fixed date and time to run the script only once at that specific time. Once all are selected, click on Save to create the trigger.

<img alt="save-trigger" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/save-trigger.jpg" data- decoding="async" height="389" src="data:image/svg xml,” width=”800″>

If you haven’t given permission to run the script like I told you before, then you’ll be asked to give permission before creating the trigger.

Based on your selection, the trigger will run continuously. If it faces any problem, it will notify you along with the error that occurred.

Now, let’s dive into some practical examples of how you can use Google Apps Script to automate your Gmail tasks.

Send Recurring Emails

function sendRecurringEmail() {
  var recipient = "[email protected]";
  var subject = "Your subject here";
  var message = "Your custom message here";

  GmailApp.sendEmail(recipient, subject, message);
}

Gmail lets you schedule emails, but not recurring emails. Whether you want to remind someone something or you want to make sure your email isn’t overlooked. This simple scripts sends an email to the provided address with the subject and message you provide. You can then set up a recurring trigger from the Triggers option.

In the script, edit the recipient, subject, and message section with the actual details. Make sure the quotes around the example text stay. For example, the subject should look like this:

var subject = "Important Reminder";
<img alt="send-recurring-email-script" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/send-recurring-email-script.jpg" data- decoding="async" height="307" src="data:image/svg xml,” width=”800″>

Since the triggers have a maximum limit of up to a month, the recurring message must be sent once every month. Unfortunately, this means you can’t use it to send wishes for occasions that happen on a yearly basis.

<img alt="example-email" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/example-email.jpg" data- decoding="async" height="357" src="data:image/svg xml,” width=”800″>

Filter Emails With Links to a Label

function processUnreadEmailsWithLinks() {
  var labelName = 'Emails with Links';
  var label = GmailApp.getUserLabelByName(labelName);
  if (!label) {
    label = GmailApp.createLabel(labelName);
  }
  var threads = GmailApp.search('is:unread');
  for (var i = 0; i < threads.length; i  ) {
    var messages = threads[i].getMessages();
    for (var j = 0; j < messages.length; j  ) {
      var message = messages[j];
      var body = message.getBody();
      if (bodyContainsLinks(body)) {
        label.addToThread(threads[i]);
      }
    }
  }
}

function bodyContainsLinks(body) {
  var regex = /https?://[^s"'] /g;
  return regex.test(body);
}

Emails with links in the body are usually more important. Whether you receive reports from a colleague or you have subscribed to newsletters that send specific resources, categorizing emails with links can be very useful.

This script looks at all the unread emails in your Gmail account and separates the ones with links in the email body to a new label named “Emails with Links”. By default, it will look everywhere in Gmail for emails, but you can narrow down the search by editing the var threads = GmailApp.search('is:unread'); line. Below are some ways you can edit it:

Search only in Inbox: var threads = GmailApp.search('in:inbox is:unread');

Search in other labels: var threads = GmailApp.search('in:inbox is:unread OR in:promotions is:unread OR in:important is:unread');

Search all read/unread emails in Inbox: var threads = GmailApp.search('in:inbox');

Search emails from a specific sender: var threads = GmailApp.search('from:[email protected]');

<img alt="filtered-emails-with-links" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/filtered-emails-with-links.jpg" data- decoding="async" height="245" src="data:image/svg xml,” width=”800″>

These examples should give you an idea of how you can edit the script to narrow down the emails with links. Also, I believe setting up a daily trigger will be more than enough for such types of emails.

Automatically Delete Old Emails

function deleteOldEmails() {
  var threads = GmailApp.search('older_than:30d');
  for (var i = 0; i < threads.length; i  ) {
    threads[i].moveToTrash();
  }
}

If you don’t want to keep old emails, then you can use this script to delete emails that are older than a specific period. The script here will look for all emails in Gmail that are older than 30 days and send them to Trash. You can edit the 'older_than:30d'part to specify how old emails you want to delete, like 'older_than:180d'.

<img alt="automatically-delete-old-emails" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/automatically-delete-old-emails.jpg" data- decoding="async" height="285" src="data:image/svg xml,” width=”800″>

If you want to delete emails from a specific label instead, then you can edit Gmail.App.search part to include the label. Like this:

var threads = GmailApp.search('in:inbox older_than:30d');

To make the process automatic, create a trigger that automatically runs the script every few days. Depending on how old emails you want to delete, I am sure a weekly trigger or even a monthly one will be fine.

Save All Email Addresses To Google Sheets

function getEmailAddresses() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetName = "Email Addresses";
  var sheet = ss.getSheetByName(sheetName);
  
  if (!sheet) {
    sheet = ss.insertSheet(sheetName);
    sheet.appendRow(["Email Address"]);
  }
  
  var threads = GmailApp.getInboxThreads();
  var emailAddresses = [];
  
  var existingData = sheet.getDataRange().getValues();
  if (existingData.length > 1) {
    var existingEmailAddresses = existingData.slice(1).flat();
  } else {
    var existingEmailAddresses = [];
  }
  
  for (var i = 0; i < threads.length; i  ) {
    var messages = threads[i].getMessages();
    for (var j = 0; j < messages.length; j  ) {
      var emailAddress = messages[j].getFrom();
      if (emailAddresses.indexOf(emailAddress) === -1 && existingEmailAddresses.indexOf(emailAddress) === -1) {
        emailAddresses.push(emailAddress);
      }
    }
  }
  
  for (var k = 0; k < emailAddresses.length; k  ) {
    sheet.appendRow([emailAddresses[k]]);
  }
}

This script will search Gmail for all the emails and copy the name and email address of the senders/recipients and save them in Google Sheets. There can be many uses for this, like creating a mailing list for email marketing or creating a record of everyone who contacts you.

However, creating this script is a little different from others since you need to open Google Apps Script from inside the Google Sheets so it can identify the sheet. It’s only needed to be done for the first time though. Here’s how:

Open a new sheet in Google Sheets. Here click on Extensions in the above menu and then select Apps Script. This will open Google Apps Script and you can add the script and run it as I demonstrated before.

<img alt="google-sheets-create-apps-script" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/google-sheets-create-apps-script.jpg" data- decoding="async" height="299" src="data:image/svg xml,” width=”800″>

The script will create a new Sheet with the name “Email Addresses” with the name and email address written in the same cell. You won’t need to open the sheet again in the future for each trigger. Any new email address will be updated in the sheet at the end without any duplicates.

<img alt="save-email-address-google-sheets" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/save-email-address-google-sheets.jpg" data- decoding="async" height="537" src="data:image/svg xml,” width=”800″>

Depending on how frequently you receive emails from new senders, a daily or weekly trigger should be good.

Save Email Attachments To Google Drive Automatically

function onNewEmail(e) {
  var threads = GmailApp.getInboxThreads(0, 1);
  var messages = threads[0].getMessages();
  
  var folderName = "Email Attachments";
  var folderIterator = DriveApp.getFoldersByName(folderName);
  var folder;

  if (folderIterator.hasNext()) {
    folder = folderIterator.next();
  } else {
    folder = DriveApp.createFolder(folderName);
  }
  
  for (var i = 0; i  0) {
      var attachments = message.getAttachments();
      
      for (var j = 0; j < attachments.length; j  ) {
        var attachment = attachments[j];
        var attachmentHash = Utilities.base64Encode(Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, attachment.getBytes()));
        var existingFiles = folder.getFiles();

        var isDuplicate = false;

        while (existingFiles.hasNext()) {
          var existingFile = existingFiles.next();
          var existingFileHash = Utilities.base64Encode(Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, existingFile.getBlob().getBytes()));

          if (attachmentHash === existingFileHash) {
            isDuplicate = true;
            break;
          }
        }

        if (!isDuplicate) {
          folder.createFile(attachment);
        }
      }
    }
  }
}

A very handy script if you receive important attachments often via email. This will not only preserve attachments but also group them together in a much better interface to manage them.

This script is coded to only work on new emails that you will receive after the time it ran for the first time. It will automatically create a new folder named “Email Attachments” in Google Drive if not available. I have also avoided using names for checking duplicate files since they can be the same for different files. The script instead checks for an MD5 hash value that is unique based on file content.

<img alt="save-new-attachments-google-drive" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/save-new-attachments-google-drive.jpg" data- decoding="async" height="394" src="data:image/svg xml,” width=”800″>

I know not everyone wants to save new attachments only and may want attachments from already received emails too. For this, below is a modified script that follows the same rules but saves attachments from currently present emails instead. However, it will take quite some time to save all depending on how many attachments you have.

function saveAllAttachmentsToDrive() {
  var folderName = "Email Attachments";
  var folderIterator = DriveApp.getFoldersByName(folderName);
  var folder;
  
  if (folderIterator.hasNext()) {
    folder = folderIterator.next();
  } else {
    folder = DriveApp.createFolder(folderName);
  }

  var threads = GmailApp.getInboxThreads();

  for (var i = 0; i < threads.length; i  ) {
    var messages = threads[i].getMessages();
    
    for (var j = 0; j < messages.length; j  ) {
      var message = messages[j];
      var attachments = message.getAttachments();
      
      for (var k = 0; k < attachments.length; k  ) {
        var attachment = attachments[k];
        var attachmentHash = Utilities.base64Encode(Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, attachment.getBytes()));
        var existingFiles = folder.getFiles();
        var isDuplicate = false;

        while (existingFiles.hasNext()) {
          var existingFile = existingFiles.next();
          var existingFileHash = Utilities.base64Encode(Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, existingFile.getBlob().getBytes()));

          if (attachmentHash === existingFileHash) {
            isDuplicate = true;
            break;
          }
        }

        if (!isDuplicate) {
          folder.createFile(attachment);
        }
      }
    }
  }
}

Get Daily Inspirational Quote

function sendDailyQuoteEmail() {
  var apiKey = 'YOUR_API_KEY';
  var endpoint = 'https://quotes.rest/qod';

  var response = UrlFetchApp.fetch(endpoint, {
    headers: {
      'X-TheySaidSo-Api-Secret': apiKey
    }
  });

  var data = JSON.parse(response.getContentText());
  var quoteContents = data.contents.quotes[0];
  var quote = quoteContents.quote;
  var author = quoteContents.author;

  var recipient = '[email protected]';
  var subject = 'Daily Quote';
  var message = `Here is your daily quote:nn"${quote}"nn- ${author}`;

  GmailApp.sendEmail(recipient, subject, message);
}

It may not have a direct use in your work or email management, but it’s great for getting pumped up to give your all every day right in the inbox. When properly set up, this script will use They Said So API to send you their daily inspirational quote via email. Here’s how to set it up:

First, you need a personal API key from They Said So. On the They Said So API page you can register a free account to get the key. It gives 5 calls for free, which is more than enough for a daily quote.

Once you have the key, replace the YOUR_API_KEY part with the actual key you got from They Said So. You also need to replace the [email protected] part with your actual email address or someone else’s if you want to set it up for someone else.

<img alt="get-daily-quotes-google-apps-script" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/get-daily-quotes-google-apps-script.jpg" data- decoding="async" height="443" src="data:image/svg xml,” width=”800″>

Now all you need to do is set up a trigger that runs on a daily basis, since running it earlier than that will only resend the current day’s quote.

<img alt="daily-quote-delivered" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/daily-quote-delivered.jpg" data- decoding="async" height="304" src="data:image/svg xml,” width=”800″>

Final Words

I personally didn’t have any problem running all of these scripts together, and neither I reach the daily quota. I am sure you’ll be fine, too, as long as you don’t use too aggressive triggers. You should also keep a check on these scripts to ensure no script is facing any errors.