(+91)7275894867 [email protected]
OutRightCRM Login
๐Ÿ“… Published on May 5, 2025

Gmail Automation

Author Avatar
Author
Editorial Team

Gmail Automation

This is where the Gmail Automation with Google Sheets comes in. Built using Google Apps Script and seamlessly integrated with Google Sheets, this powerful automation tool helps you take full control of your Gmail inbox. In this guide, youโ€™ll discover how Gmail Automation with Google Sheets can save you time, keep you organized, and ensure that no important message ever slips through the cracks.
  1. Step 1: Click on the Copy button to copy the code snippet.
  2. Step 2: Paste the copied code into your project’s script editor.

Apps Scripts Blog

Read Blog

Apps Scripts Code

// =====================
// RUN ON SHEET OPEN
// =====================
function onOpen() {
    menu();
    listTotalEmails();
  }
  
  // =====================
  // CUSTOM MENU
  // =====================
  function menu() {
    const ui = SpreadsheetApp.getUi();
    ui.createMenu('๐Ÿ“ง Gmail Tools')
      .addItem('๐Ÿ“จ Total Emails', 'listTotalEmails')
      .addItem('๐Ÿ“ฅ Unread Emails', 'countUnreadEmails')
      .addItem('๐Ÿ” Filter by Keyword', 'filterAndSortEmails')
      .addItem('๐Ÿ“ฌ Send Gmail Summary', 'sendEmailSummary')
      .addItem('๐Ÿงน Clean Mail (Old + Spam)', 'showSidebar')
      .addItem('๐Ÿ”„ Reload Old/Spam Emails', 'reloadOldAndSpamEmails')
      .addItem('๐Ÿ“ค Forward Emails by Keyword', 'forwardEmailsByKeyword')
      .addToUi();
  }
  
  // =====================
  // 1. TOTAL EMAILS
  // =====================
  function listTotalEmails() {
    const threads = GmailApp.search("");
    const ss = SpreadsheetApp.getActiveSpreadsheet();
    let sheet = ss.getSheetByName("Total Emails") || ss.insertSheet("Total Emails");
    sheet.clearContents();
    sheet.appendRow(["Sender", "Subject", "Date"]);
  
    threads.forEach(thread => {
      const msg = thread.getMessages()[0];
      sheet.appendRow([msg.getFrom(), msg.getSubject(), msg.getDate()]);
    });
  
    beautifySheet(sheet);
    SpreadsheetApp.getUi().alert(`๐Ÿ“ฌ Total Emails Found: ${threads.length}`);
  }
  
  // =====================
  // 2. UNREAD EMAILS (WITH OPEN LINK)
  // =====================
  function countUnreadEmails() {
    const unreadEmails = GmailApp.search("is:unread");
    SpreadsheetApp.getUi().alert(`You have ${unreadEmails.length} unread email(s).`);
    writeUnreadEmailsToSheet(unreadEmails);
  }
  
  function writeUnreadEmailsToSheet(unreadEmails) {
    const ss = SpreadsheetApp.getActiveSpreadsheet();
    let sheet = ss.getSheetByName("Unread Emails") || ss.insertSheet("Unread Emails");
    sheet.clearContents();
    sheet.appendRow(["Sender", "Subject", "Date", "Open"]);
  
    unreadEmails.forEach(thread => {
      const msg = thread.getMessages()[0];
      const sender = msg.getFrom();
      const subject = msg.getSubject();
      const date = msg.getDate();
      const threadId = thread.getId();
      const url = `https://mail.google.com/mail/u/0/#inbox/${threadId}`;
      const openLink = `=HYPERLINK("${url}", "Open")`;
  
      sheet.appendRow([sender, subject, date, openLink]);
    });
  
    beautifySheet(sheet);
  }
  
  // =====================
  // 3. FILTER EMAILS BY KEYWORD
  // =====================
  function filterAndSortEmails() {
    const ui = SpreadsheetApp.getUi();
    const keyword = ui.prompt("Enter keyword to filter unread emails:").getResponseText().trim();
    if (!keyword) return ui.alert("โŒ Please enter a valid keyword.");
  
    const filteredEmails = GmailApp.search(`is:unread ${keyword}`);
    let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Filtered Emails") || SpreadsheetApp.getActiveSpreadsheet().insertSheet("Filtered Emails");
    sheet.clearContents();
    sheet.appendRow(["Sender", "Subject", "Date"]);
  
    filteredEmails.forEach(thread => {
      const msg = thread.getMessages()[0];
      sheet.appendRow([msg.getFrom(), msg.getSubject(), msg.getDate()]);
    });
  
    beautifySheet(sheet);
    ui.alert(`โœ… Found ${filteredEmails.length} unread emails with keyword "${keyword}".`);
  }
  
  // =====================
  // 4. GMAIL SUMMARY EMAIL
  // =====================
  function sendEmailSummary() {
    const totalEmails = GmailApp.search("").length;
    const unreadEmails = GmailApp.search("is:unread").length;
  
    const oldDate = new Date();
    oldDate.setDate(oldDate.getDate() - 30);
    const oldEmails = GmailApp.search(`before:${Utilities.formatDate(oldDate, Session.getScriptTimeZone(), "yyyy/MM/dd")}`).length;
  
    const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    const file = DriveApp.getFileById(spreadsheet.getId());
    const sheetUrl = spreadsheet.getUrl();
    file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
  
    const summary = `
  ๐Ÿ“Š Gmail Summary Report
  -------------------------------
  ๐Ÿ“จ Total Emails: ${totalEmails}
  ๐Ÿ“ฅ Unread Emails: ${unreadEmails}
  ๐Ÿ—‘๏ธ Emails Older Than 30 Days: ${oldEmails}
  ๐Ÿ“Ž Sheet: ${sheetUrl}`;
  
    MailApp.sendEmail(Session.getActiveUser().getEmail(), "๐Ÿ“ฌ Gmail Summary Report", summary);
    SpreadsheetApp.getUi().alert("โœ… Summary email sent.");
  }
  
  // =====================
  // 5. CLEAN MAIL - OLD + SPAM
  // =====================
  function listOldAndSpamEmails() {
    const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Clean Mail") ||
                  SpreadsheetApp.getActiveSpreadsheet().insertSheet("Clean Mail");
    sheet.clearContents();
    sheet.appendRow(["Sender", "Subject", "Date", "Type"]);
  
    const threadMap = {};
  
    const oldDate = new Date();
    oldDate.setDate(oldDate.getDate() - 30);
    const oldThreads = GmailApp.search(`before:${Utilities.formatDate(oldDate, Session.getScriptTimeZone(), "yyyy/MM/dd")}`);
    oldThreads.forEach(thread => {
      const msg = thread.getMessages()[0];
      const key = msg.getFrom() + msg.getSubject() + msg.getDate();
      threadMap[key] = thread.getId();
      sheet.appendRow([msg.getFrom(), msg.getSubject(), msg.getDate(), "Old"]);
    });
  
    const spamThreads = GmailApp.search("in:spam");
    spamThreads.forEach(thread => {
      const msg = thread.getMessages()[0];
      const key = msg.getFrom() + msg.getSubject() + msg.getDate();
      threadMap[key] = thread.getId();
      sheet.appendRow([msg.getFrom(), msg.getSubject(), msg.getDate(), "Spam"]);
    });
  
    beautifySheet(sheet);
    PropertiesService.getDocumentProperties().setProperty("threadMap", JSON.stringify(threadMap));
  }
  
  function deleteEmailsByType(type) {
    const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Clean Mail");
    const data = sheet.getDataRange().getValues();
    const map = JSON.parse(PropertiesService.getDocumentProperties().getProperty("threadMap") || "{}");
  
    for (let i = data.length - 1; i > 0; i--) {
      if (data[i][3] === type) {
        const key = data[i][0] + data[i][1] + data[i][2];
        const id = map[key];
        if (id) GmailApp.getThreadById(id).moveToTrash();
        sheet.deleteRow(i + 1);
      }
    }
  
    SpreadsheetApp.getUi().alert(`โœ… Deleted all "${type}" emails.`);
  }
  
  function deleteOldEmails() {
    deleteEmailsByType("Old");
  }
  
  function deleteSpamEmails() {
    deleteEmailsByType("Spam");
  }
  
  function reloadOldAndSpamEmails() {
    listOldAndSpamEmails();
    SpreadsheetApp.getUi().alert("โœ… Old and Spam emails reloaded.");
  }
  
  // =====================
  // 6. FORWARD EMAILS
  // =====================
  function forwardEmailsByKeyword() {
    const ui = SpreadsheetApp.getUi();
    const keyword = ui.prompt("Enter keyword to find unread emails:").getResponseText().trim();
    const email = ui.prompt("Enter email to forward to:").getResponseText().trim();
    if (!keyword || !email.includes("@")) return ui.alert("โŒ Invalid input.");
  
    const threads = GmailApp.search(`is:unread ${keyword}`);
    threads.forEach(thread => {
      const msg = thread.getMessages()[0];
      GmailApp.sendEmail(email, `FWD: ${msg.getSubject()}`, msg.getBody(), { htmlBody: msg.getBody() });
    });
  
    ui.alert(`โœ… Forwarded ${threads.length} email(s) to ${email}`);
  }
  
  // =====================
  // 7. SIDEBAR UI
  // =====================
  function showSidebar() {
    const html = HtmlService.createHtmlOutputFromFile("Sidebar").setTitle("๐Ÿงน Gmail Cleanup");
    SpreadsheetApp.getUi().showSidebar(html);
  }
  
  // =====================
  // 8. FORMATTING FUNCTION
  // =====================
  function beautifySheet(sheet) {
    const range = sheet.getDataRange();
    const numRows = range.getNumRows();
    const numCols = range.getNumColumns();
  
    sheet.setFrozenRows(1);
  
    const header = sheet.getRange(1, 1, 1, numCols);
    header.setFontWeight("bold").setFontColor("white").setBackground("#4A90E2").setHorizontalAlignment("center");
  
    range.setBorder(true, true, true, true, true, true);
  
    for (let r = 2; r <= numRows; r++) {
      const color = r % 2 === 0 ? "#F9F9F9" : "#FFFFFF";
      sheet.getRange(r, 1, 1, numCols).setBackground(color);
    }
  
    for (let c = 1; c <= numCols; c++) sheet.autoResizeColumn(c);
  }
  
  

Sidebar Code


<!DOCTYPE html>
<html>
<head>
  <base target="_top">
  <style>
    body { font-family: Arial, sans-serif; padding: 15px; }
    h3 { color: #333; }
    button {
      width: 100%; padding: 10px; margin-top: 10px;
      background: #4285F4; color: white; border: none;
      border-radius: 4px; cursor: pointer; font-size: 14px;
    }
    button:hover { background: #3367d6; }
    .note {
      margin-top: 15px; font-size: 12px;
      background: #f1f1f1; padding: 10px;
      border-left: 4px solid #4A90E2;
    }
  </style>
</head>
<body>
  <h3>๐Ÿงน Gmail Cleanup</h3>
  <button onclick="google.script.run.withSuccessHandler(refresh).deleteOldEmails()">๐Ÿ—‘๏ธ Delete Old Emails</button>
  <button onclick="google.script.run.withSuccessHandler(refresh).deleteSpamEmails()">๐Ÿšซ Delete Spam Emails</button>
  <button onclick="google.script.run.withSuccessHandler(refresh).reloadOldAndSpamEmails()">๐Ÿ”„ Reload Old/Spam Emails</button>
  <div class="note">
    Make sure you've reloaded emails before deleting. <br>
    This refreshes the list of old and spam emails in the sheet.
  </div>

  <script>
    function refresh() {
      alert("โœ… Done!");
    }
  </script>
</body>
</html>
 

Scroll to Top