// =====================
// 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);
}
๐ Copy 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>
๐ Copy Code