Gmail Automation: 8 Useful Google Scripts to Automate Your Gmail

Automate Gmail Featured

Gmail, by itself, is already a very powerful email client. With the help of filters, you can set up automation to better organize your inbox. However, for power users, the filter feature is not sufficient compared to writing custom scripts. These eight Google scripts can further automate your Gmail.

Tip: try another easy Gmail tip: set up automatic forwarding in Gmail.

1. Auto Delete Email After X Number of Days

Very often after reading email, we just keep them in our inbox regardless of how useful they are. Now that Google has put a limit on space, you may want to clean up your inbox and get rid of those useless emails. The following script can check for email with the “Delete Me” label and delete them after “X” number of days.

  1. Make sure you’re logged in to your Google account, go to Google Scripts and create a new project.
Automate Gmail New Project
  1. Paste the following script and save it. You can change the number of days (the variable delayDays) that pass before it deletes the email messages from your inbox.
function auto_delete_mails() {  
  var label = GmailApp.getUserLabelByName("Delete Me");  
  if(label == null) {
    GmailApp.createLabel('Delete Me');
  }
  else {
    var delayDays = 2; // Enter # of days before messages are moved to trash   
    var maxDate = new Date(); 
    maxDate.setDate(maxDate.getDate()-delayDays);    
    var threads = label.getThreads();  
    for (var i = 0; i < threads.length; i++) {  
      if (threads[i].getLastMessageDate()<maxdate) {
        threads[i].movetotrash();
      }
    }
  }
}
  1. Create a new trigger to run your script on a schedule. Open “the schedule icon on the left side menu -> Triggers -> Add Trigger.”
Automate Gmail Triggers
  1. Customize your trigger’s settings to run the script every hour (or however often you wish), then scroll down and click “Save.”
Automate Gmail Add Trigger

Once this script runs, it will create a new label, “Delete Me,” in your Gmail account. Tag your unwanted emails with this label, and they will be deleted after the number of days specified in your script.

Tip: If your email seems like it’s getting out of hand, read through our review of SaneBox and see if it can help you get a handle on your email.

2. Archive All Old Emails

If you want an option less dangerous than deleting email, you can create a script to archive all of your old email by following the steps below.

  1. Create a new Google script with the following code:
function archiveOldEmails() {
  // Get all the threads in the inbox
  var threads = GmailApp.getInboxThreads();
 
  // Loop through all the threads
  for (var i = 0; i < threads.length; i++) {
    var thread = threads[i];
    var messages = thread.getMessages();
 
    // Loop through all the messages in the thread
    for (var j = 0; j < messages.length; j++) {
      var message = messages[j];
      var age = (new Date() - message.getDate()) / (1000 * 60 * 60 * 24);
 
      // If the message is older than 30 days, archive it
      if (age > 30) {
        thread.moveToArchive();
      }
    }
  }
}
  1. Create a trigger (as shown above) to run the script every day.

At your chosen time, the script will run and move the emails from your inbox to the archive. These archived emails will still be available in the “All Mail” section.

Good to know: if you don’t care about the emails in your inbox and just want to clean it all up quickly, this guide shows you how to mark all of your unread emails as read and delete them.

3. Get SMS Notifications for Important Email

This Google script makes use of Google Calendar’s SMS feature to send you an SMS when you get an important email.

  1. Create a new Google script with the following code:
function Gmail_send_sms(){
  var label = GmailApp.getUserLabelByName("Send Text");  
  if(label == null){
    GmailApp.createLabel('Send Text');
  }
  else{
    var threads = label.getThreads();  
    var now = new Date().getTime();
    for (var i = 0; i < threads.length; i++) {  
      var message = threads[i].getMessages()[0];
      var from = message.getFrom();
      var subject = message.getSubject();
      CalendarApp.createEvent(subject, new Date(now+60000), new Date(now+60000), {location: from}).addSmsReminder(0);
    }
    label.removeFromThreads(threads);
  }
}
  1. Save it and create a trigger for it to run every five minutes.
  2. Create a new Gmail filter that automatically adds the “Send Text” label to your chosen incoming emails. In Gmail, click the Search Options icon in the top search bar.
Automate Gmail 2 Search Bar Options 1
  1. Customize the criteria for the SMS notifications that will alert you that you have important email in your inbox, then click “Create filter.”
Automate Gmail 2 Search Filters
  1. Check “Apply the label,” choose “Send Text” and click “Create filter.”
Automate Gmail 2 Filter Send Text

The script will scan your inbox every five minutes. When it detects an email with the “Send Text” label, it will immediately create an event in Google Calender, which will trigger the SMS

Tip: you can also send SMS text messages from your PC.

4. Create a Summary of Your Emails

Instead of reading all of your email individually, you can write a script to create a single email summary of your unread email.

  1. Create a new Google Script with the following code:
function createEmailSummary() {
    // Search for unread emails
    var threads = GmailApp.search("is:unread");
    var summary = "Unread Emails:\n";
    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];
        summary += message.getFrom() + ": " + message.getSubject() + "\n";
      }
    }
 
    // Search for emails with specific keywords in the subject
    var threads = GmailApp.search("subject:(important meeting)");
    summary += "\nEmails with keyword 'important meeting' in the subject:\n";
    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];
        summary += message.getFrom() + ": " + message.getSubject() + "\n";
      }
    }
 
    // You can add more search criteria here
    // ...
 
    // Send the summary as an email
    GmailApp.sendEmail("youremail@example.com", "Email Summary", summary);
}
  1. Change “youremail@example.com” to your email.
  2. Create a new trigger to run the script every day.
Automate Gmail 4 Summary Example

When the script runs, it’ll send you an email that includes how many of each type of email you haven’t read yet. The script above is a good starting point – it counts the number of emails with “important meeting” in the subject. You can adjust the script to count your desired search criteria.

5. Save Email as PDFs in Google Drive

If you have an email that you want to archive in Google Drive, you can use a Google script to save it as a PDF in your Google Drive account. The following script will save all of the messages in an email thread as one PDF file in your Google Drive. If the email has attachments, it will create a folder and store the messages and attachments within.

  1. Create a new Google script with the following code:
function save_Gmail_as_PDF() {
  // Get the label "Save As PDF" or create it if it doesn't exist
  var label = GmailApp.getUserLabelByName("Save As PDF");  
  if(label == null){
    label = GmailApp.createLabel('Save As PDF');
  }
 
  // Get the threads with the label
  var threads = label.getThreads();  
  for (var i = 0; i < threads.length; i++) {    
    var messages = threads[i].getMessages();
    var subject = messages[0].getSubject();
    var bodys = [];
    // Loop through all messages in thread
    for(var j = 0; j < messages.length; j++){  
      var message = messages[j];
      bodys.push({
        body: message.getPlainBody(),
        from: message.getFrom(),
      });
      var attachments  = message.getAttachments();
      var temp_attach = message.getAttachments();
      if(temp_attach.length > 0){
        for(var k =0; k < temp_attach.length; k++){
          attachments.push(temp_attach[k]);
        }
      }
    }
    // Create a Google Docs document from the message body
    var bodyDoc = DocumentApp.create(subject);
    var bodyDocId = bodyDoc.getId();
    var bodyDocFile = DriveApp.getFileById(bodyDocId);
    var bodyDocBody = bodyDoc.getBody();
    bodyDocBody.setText(bodys.map(obj => `From: ${obj.from}\n${obj.body}`).join('\n\n'));
    bodyDoc.saveAndClose();
 
    // Convert the Google Docs document to a PDF
    var blob = bodyDocFile.getAs('application/pdf');
    var pdfFile = DriveApp.createFile(blob);
 
    // If there are attachments
    if(attachments.length > 0){
      // Create a folder in Drive with the message subject
      var folder = DriveApp.createFolder(subject);
      for (var j = 0; j < attachments.length; j++) {
        folder.createFile(attachments[j]);
      }
      // Add the PDF file of the message body to the folder
      folder.createFile(pdfFile);
    }
    // Remove the Google Docs document from Google Drive
    DriveApp.getFileById(bodyDocId).setTrashed(true);
    // Remove the label from the thread
    label.removeFromThread(threads[i]);
  }
}
  1. Save it and set a trigger for it to run at a regular interval.
Automate Gmail 5 Saved Email Pdf

When you want to save an email and its attachments to Google Drive, simply tag it with the “Save to PDF” label. The body of each email and the sender, in each thread, will be shown in order, starting with the oldest.

Good to know: not sure how many files you have in your Google Drive folder? This guide shows you how to find out.

6. Automatically Send Followup Emails

You may not always get a swift response to your emails. To tackle this problem, you can send a follow-up email to remind the email recipients. Instead of writing each followup manually, you can send them automatically with a script!

  1. Create a new Google script with the following code:
function sendFollowupEmails() {
  const startDate = new Date('2023-01-01');
 
  const daysAgo = 3;
  var dateInPast = new Date();
  dateInPast.setDate(dateInPast.getDate() - daysAgo);
 
  var threads = GmailApp.search("is:sent before:" + dateInPast.toLocaleDateString() + " after:" + startDate.toLocaleDateString());
 
  for (var i = 0; i < threads.length; i++) {
    var conversation = threads[i];
 
    var foundResponse = false;
    // If a sent thread has more than 1 email, we don’t need to followup
    // because we either followed up already or they responded.
    if (conversation.getMessages().length > 1) {
      foundResponse = true;
    }
 
    if (!foundResponse) {
      var body = "Hi, I just wanted to follow up on my previous email. If I get no reply I will assume you are not interested. \n\nBest regards,\n[Your Name]";
      conversation.replyAll(body);
    }
  }
}
  1. Customize a few things in this script:
  • Change startDate to a time nearer the present day to not resurrect very old threads.
  • Change daysAgo to customize how old you want an email to be before you send a follow-up.
  • Change [Your Name] to your name.
  1. Save it and set a trigger to run every seven days.

Keep emailing normally, and the script will automatically handle follow-ups.

7. Label Emails According to Subject Keyword

If you get swamped with emails but don’t want to delete most of them, you can use this script to label and organize them based on their content.

  1. Create a new Google script with the following code:
function categorizeEmails() {
  const emailsToGet = 50;
  var keywords = {
    "promo": "Promotions",
    "offer": "Promotions",
    "discount": "Promotions",
    "newsletter": "Newsletters",
    "action": "Todo",
    "required": "Todo",
    "shipped": "Orders",
    "delivered": "Orders",
    "receipt": "Orders",
    "invoice": "Orders"
  };
 
  var threads = GmailApp.getInboxThreads(0, emailsToGet);
 
  for (var i = 0; i < threads.length; i++) {
    var subject = threads[i].getFirstMessageSubject().toLowerCase();
    var labels = GmailApp.getUserLabels();
    var foundLabel = false;
 
    for (var keyword in keywords) {
      if (subject.indexOf(keyword) !== -1) {
        for (var j = 0; j < labels.length; j++) {
          if (labels[j].getName() === keywords[keyword]) {
            threads[i].addLabel(labels[j]);
            foundLabel = true;
            break;
          }
        }
 
        if (!foundLabel) {
          GmailApp.createLabel(keywords[keyword]);
          threads[i].addLabel(GmailApp.getUserLabelByName(keywords[keyword]));
        }
 
        break;
      }
    }
  }
}
  1. You can customize the number of emails affected with the variable emailsToGet or keywords and labels with the variable keywords.
  2. Save the script and set a trigger to run every few minutes or hours.
Automate Gmail 7 Emails Labeled By Subject

This allows you to stay on top of things by viewing only emails with a specific label. This script works well on most of your email, saving you from simply deleting them.

Tip: set up multiple signatures in Gmail and quickly switch between them for different audiences.

8. Forward Certain Emails to Multiple Other Addresses

While Gmail has a built-in way to forward email to another email address, it can’t easily forward email with a certain criteria to multiple email addresses, but this script can.

  1. Create a new script with the following code:
function emailForwarding() {
  const emailsToGet = 50;
  var criteria = [
    {
      sender: "example1@maketecheasier.com",
      subjectContains: "invoice",
      forwardTo: ["example2@maketecheasier.com", "example3@maketecheasier.com"]
    },
    {
      sender: "example4@maketecheasier.com",
      subjectContains: "urgent",
      forwardTo: ["example5@maketecheasier.com", "example6@maketecheasier.com"]
    }
  ];
 
  var label = GmailApp.getUserLabelByName("Forwarded");
  if (!label) {
    label = GmailApp.createLabel("Forwarded");
  }
 
  var threads = GmailApp.search("is:inbox", 0, emailsToGet);
  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    console.log('thread id:', threads[i].getId());
    for (var j = 0; j < messages.length; j++) {
 
      var message = messages[j];
      var sender = message.getFrom();
      var subject = message.getSubject().toLowerCase();
      console.log('sender', sender, 'subject', subject);
      for (var k = 0; k < criteria.length; k++) {
        var rule = criteria[k];
        if (sender.indexOf(rule.sender) != -1 && subject.indexOf(rule.subjectContains) != -1) {
          var recipient = rule.forwardTo.join(",");
          GmailApp.sendEmail(recipient, subject, message.getPlainBody(), {cc: sender});
          threads[i].addLabel(label);
        }
      }
    }
  }
}
  1. Customize the criteria as needed.
  2. Create a trigger that will run the script every few minutes or hours.

Your Gmail will automatically forward email that matches your criteria to two or more email addresses.

Good to know: Gmail has a built-in method to auto respond to email if you’re on vacation or out of office.

Frequently Asked Questions

Is Google Apps Script free to use?

Yes, Google Apps Script is free to use as long as you have a Gmail account. However, there are dozens of quotas and limitations on your usage. Google may change these at any time, but at the time of writing, they include nearly 40 features, such as documents created, email read/write, spreadsheets created, and triggers total runtime. Free accounts have a very low limit, while Google Workspace has a much higher limit.

Can I use Google Apps Script to access data from other services?

Yes, Google Apps Script isn’t limited to working with Google services. You access data from external non-Google services on the internet (for example, the Pokémon API) using built-in classes such as UrlFetchApp like so:

var response = UrlFetchApp.fetch("https://pokeapi.co/api/v2/pokemon/ditto");
Logger.log(response.getContentText()); // All details of Ditto would be logged

What do I do if I get errors in my Google Apps Script?

You can debug your code to identify and fix the error. Luckily, Google Apps Script has a built-in debugger that you can use to troubleshoot your code. To use it, simply open the script editor and click Debug. From there, you can set breakpoints, step through your code, and inspect variables to help identify any issues.

Image credit: Pexels. All screenshots by Brandon Li.

Is this post useful?
Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

Brandon Li

Brandon Li is a technology enthusiast with experience in the software development industry. As a result, he has a lot of knowledge about computers and is passionate about sharing that knowledge with other people. While he has mainly used Windows since early childhood, he also has years of experience working with other major operating systems.