-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCode.gs
More file actions
465 lines (389 loc) · 17.5 KB
/
Code.gs
File metadata and controls
465 lines (389 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
// ============================================================
// Gmail Auto-Cleanup v1.1
// by O-CMO (o-cmo.com)
//
// Automatically deletes unwanted emails based on your rules.
// Set up once — runs daily on autopilot.
//
// NEW IN v1.1:
// - Detailed email reports with sample subject lines
// - Telegram notifications
// - History log in Google Sheet
//
// HOW TO USE:
// 1. Edit the RULES array below with your cleanup rules
// 2. Run dryRun() first to preview what will be deleted
// 3. Run setupDailyTrigger() to enable daily auto-cleanup
// ============================================================
// ========================
// CONFIGURATION
// ========================
const CONFIG = {
// When to run daily cleanup (hour in 24h format, e.g. 6 = 6:00 AM)
TRIGGER_HOUR: 6,
// What to do with matched emails: 'trash' or 'archive'
ACTION: 'trash',
// Maximum threads to process per rule (prevents timeout)
MAX_THREADS_PER_RULE: 100,
// ---- EMAIL REPORTS ----
SEND_EMAIL_REPORT: true,
REPORT_EMAIL: '', // Leave empty = your Gmail address
INCLUDE_SAMPLES: true, // Include sample subjects in report
SAMPLES_PER_RULE: 3, // Number of sample subjects to show
// ---- TELEGRAM NOTIFICATIONS ----
SEND_TELEGRAM: false, // Set true after setting up bot (see TELEGRAM SETUP below)
TELEGRAM_BOT_TOKEN: '', // From @BotFather
TELEGRAM_CHAT_ID: '', // Your chat ID with the bot
// ---- GOOGLE SHEET LOG ----
LOG_TO_SHEET: true, // Logs every deleted email to a sheet for history
SHEET_NAME: 'Gmail Cleanup Log' // Will be auto-created in your Drive
};
// ========================
// CLEANUP RULES
// ========================
//
// HOW TO CUSTOMIZE:
// Option A (recommended): Use Claude AI to scan your inbox and generate rules.
// See claude-scan-prompt.md in the repo for the exact prompt.
// Option B: Pick a starter pack below, uncomment it, and tweak to your needs.
// Option C: Write your own rules using Gmail search operators.
//
// Each rule has:
// query — Gmail search query (same syntax as Gmail search bar)
// label — Human-readable name (shown in reports)
const RULES = [
// =============================================
// UNIVERSAL RULES (active by default)
// These are safe for any Gmail account.
// =============================================
// --- Google & Workspace ---
{ query: 'from:calendar-notification@google.com older_than:3d', label: 'Calendar Notifications' },
{ query: 'from:drive-shares-dm-noreply@google.com older_than:14d', label: 'Drive Sharing' },
{ query: 'from:comments-noreply@docs.google.com older_than:7d', label: 'Docs Comments' },
{ query: 'from:no-reply@accounts.google.com older_than:30d', label: 'Google Security' },
// --- Gmail categories ---
{ query: 'label:Promotions older_than:30d', label: 'Old Promotions' },
{ query: 'label:Social older_than:14d', label: 'Old Social' },
// --- Social ---
{ query: 'from:no-reply@linkedin.com older_than:7d', label: 'LinkedIn' },
{ query: 'from:notification@facebookmail.com older_than:7d', label: 'Facebook' },
{ query: 'from:info@twitter.com OR from:notify@twitter.com older_than:7d', label: 'X / Twitter' },
// =============================================
// STARTER PACK: FOUNDER / CEO
// Uncomment if you run a business.
// =============================================
// { query: 'from:notifications@hubspot.com older_than:14d', label: 'HubSpot' },
// { query: 'from:noreply@notion.so older_than:7d', label: 'Notion' },
// { query: 'from:no-reply@slack.com older_than:7d', label: 'Slack' },
// { query: 'from:noreply@zoom.us older_than:7d', label: 'Zoom' },
// { query: 'from:noreply@calendly.com older_than:7d', label: 'Calendly' },
// { query: 'from:invoices@stripe.com older_than:60d', label: 'Stripe Invoices' },
// { query: 'from:no-reply@intercom.com older_than:14d', label: 'Intercom' },
// { query: 'from:digest-noreply@quora.com older_than:3d', label: 'Quora Digest' },
// { query: 'from:noreply@medium.com older_than:7d', label: 'Medium' },
// { query: 'subject:"weekly digest" older_than:7d', label: 'Weekly Digests' },
// { query: 'subject:"monthly newsletter" older_than:14d', label: 'Monthly Newsletters' },
// =============================================
// STARTER PACK: DEVELOPER
// Uncomment if you code.
// =============================================
// { query: 'from:noreply@github.com older_than:14d', label: 'GitHub' },
// { query: 'from:gitlab@mg.gitlab.com older_than:14d', label: 'GitLab' },
// { query: 'from:builds@travis-ci.com older_than:7d', label: 'Travis CI' },
// { query: 'from:no-reply@circleci.com older_than:7d', label: 'CircleCI' },
// { query: 'from:noreply@vercel.com older_than:14d', label: 'Vercel' },
// { query: 'from:notification@netlify.com older_than:14d', label: 'Netlify' },
// { query: 'from:noreply@sentry.io older_than:7d', label: 'Sentry' },
// { query: 'from:info@digitalocean.com older_than:14d', label: 'DigitalOcean' },
// { query: 'from:noreply@aws.amazon.com older_than:14d', label: 'AWS' },
// { query: 'from:noreply@stackoverflow.email older_than:7d', label: 'Stack Overflow' },
// { query: 'from:noreply@npmjs.com older_than:14d', label: 'npm' },
// =============================================
// STARTER PACK: MARKETER
// Uncomment if you do marketing.
// =============================================
// { query: 'from:noreply@mailchimp.com older_than:14d', label: 'Mailchimp' },
// { query: 'from:info@semrush.com older_than:7d', label: 'Semrush' },
// { query: 'from:noreply@hootsuite.com older_than:7d', label: 'Hootsuite' },
// { query: 'from:news@ahrefs.com older_than:14d', label: 'Ahrefs' },
// { query: 'from:noreply@buffer.com older_than:7d', label: 'Buffer' },
// { query: 'from:team@canva.com older_than:14d', label: 'Canva' },
// { query: 'from:noreply@analytics.google.com older_than:14d', label: 'Google Analytics' },
// { query: 'from:googleads-noreply@google.com older_than:14d', label: 'Google Ads' },
// { query: 'from:ads-noreply@meta.com older_than:14d', label: 'Meta Ads' },
// =============================================
// YOUR CUSTOM RULES
// Add rules generated by Claude or written manually.
// =============================================
// { query: 'from:sender@example.com older_than:7d', label: 'Example Rule' },
];
// ============================================================
// CORE FUNCTIONS
// ============================================================
function cleanupGmail() {
const results = processRules_(false);
if (results.totalProcessed > 0) {
if (CONFIG.SEND_EMAIL_REPORT) sendEmailReport_(results);
if (CONFIG.SEND_TELEGRAM) sendTelegramReport_(results);
if (CONFIG.LOG_TO_SHEET) logToSheet_(results);
}
Logger.log('Gmail Cleanup complete. Total processed: ' + results.totalProcessed);
}
function dryRun() {
const results = processRules_(true);
Logger.log('');
Logger.log('============================');
Logger.log('DRY RUN COMPLETE');
Logger.log('============================');
Logger.log('Total emails that WOULD be ' + CONFIG.ACTION + 'd: ' + results.totalProcessed);
Logger.log('');
if (results.totalProcessed > 0) {
if (CONFIG.SEND_EMAIL_REPORT) sendEmailReport_(results);
if (CONFIG.SEND_TELEGRAM) sendTelegramReport_(results);
Logger.log('Dry run report sent.');
}
return results;
}
function setupDailyTrigger() {
const existing = ScriptApp.getProjectTriggers();
for (let i = 0; i < existing.length; i++) {
if (existing[i].getHandlerFunction() === 'cleanupGmail') {
ScriptApp.deleteTrigger(existing[i]);
}
}
ScriptApp.newTrigger('cleanupGmail')
.timeBased()
.atHour(CONFIG.TRIGGER_HOUR)
.everyDays(1)
.create();
Logger.log('Daily trigger created! Runs every day at ' + CONFIG.TRIGGER_HOUR + ':00');
}
function removeTrigger() {
const triggers = ScriptApp.getProjectTriggers();
let removed = 0;
for (let i = 0; i < triggers.length; i++) {
if (triggers[i].getHandlerFunction() === 'cleanupGmail') {
ScriptApp.deleteTrigger(triggers[i]);
removed++;
}
}
Logger.log(removed > 0 ? 'Trigger removed.' : 'No active triggers found.');
}
/**
* Test Telegram integration. Run this once to verify your bot works.
*/
function testTelegram() {
if (!CONFIG.TELEGRAM_BOT_TOKEN || !CONFIG.TELEGRAM_CHAT_ID) {
Logger.log('ERROR: Set TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID in CONFIG first.');
Logger.log('See TELEGRAM SETUP instructions at the bottom of this file.');
return;
}
const ok = sendTelegram_('Gmail Auto-Cleanup — Telegram test message.\n\nIf you see this, notifications are working.');
Logger.log(ok ? 'Success! Check your Telegram.' : 'Failed. Check bot token and chat ID.');
}
// ============================================================
// INTERNAL HELPERS
// ============================================================
function processRules_(isDryRun) {
const results = {
totalProcessed: 0,
rules: [],
timestamp: new Date(),
isDryRun: isDryRun
};
RULES.forEach(function(rule) {
try {
const threads = GmailApp.search(rule.query, 0, CONFIG.MAX_THREADS_PER_RULE);
const count = threads.length;
// Collect sample subjects BEFORE deleting
const samples = [];
if (count > 0 && CONFIG.INCLUDE_SAMPLES) {
const sampleCount = Math.min(CONFIG.SAMPLES_PER_RULE, count);
for (let i = 0; i < sampleCount; i++) {
const msgs = threads[i].getMessages();
if (msgs.length > 0) {
samples.push({
from: msgs[0].getFrom(),
subject: msgs[0].getSubject(),
date: msgs[0].getDate()
});
}
}
}
if (count > 0 && !isDryRun) {
if (CONFIG.ACTION === 'archive') {
threads.forEach(function(thread) { thread.moveToArchive(); });
} else {
threads.forEach(function(thread) { thread.moveToTrash(); });
}
}
const prefix = isDryRun ? 'DRY RUN: Would ' + CONFIG.ACTION + ' ' : 'Processed ';
if (count > 0) Logger.log(prefix + count + ' threads — ' + rule.label);
results.rules.push({
label: rule.label,
count: count,
query: rule.query,
status: 'ok',
samples: samples
});
results.totalProcessed += count;
} catch (e) {
Logger.log('ERROR processing rule "' + rule.label + '": ' + e.message);
results.rules.push({
label: rule.label,
count: 0,
query: rule.query,
status: 'error',
error: e.message,
samples: []
});
}
});
return results;
}
function sendEmailReport_(results) {
const email = CONFIG.REPORT_EMAIL || Session.getActiveUser().getEmail();
const prefix = results.isDryRun ? '[DRY RUN] ' : '';
const verb = results.isDryRun ? 'Would process' : 'Processed';
let html = '<div style="font-family: -apple-system, Helvetica, Arial, sans-serif; max-width: 600px; color: #1B1C1F;">';
html += '<div style="background: #1B1C1F; color: #fff; padding: 24px; border-radius: 8px 8px 0 0;">';
html += '<div style="font-size: 12px; color: #FFC82B; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 8px;">Gmail Auto-Cleanup</div>';
html += '<div style="font-size: 24px; font-weight: 700;">' + prefix + verb + ' ' + results.totalProcessed + ' emails</div>';
html += '<div style="font-size: 14px; color: #8F9194; margin-top: 8px;">' + results.timestamp.toLocaleString() + '</div>';
html += '</div>';
html += '<div style="background: #F6F7FB; padding: 24px; border-radius: 0 0 8px 8px;">';
results.rules.forEach(function(r) {
if (r.count === 0 && r.status === 'ok') return;
html += '<div style="background: #fff; border: 1px solid #CFD2D8; border-radius: 6px; padding: 16px; margin-bottom: 12px;">';
html += '<div style="display: flex; justify-content: space-between; margin-bottom: 8px;">';
html += '<strong style="font-size: 15px;">' + r.label + '</strong>';
html += '<span style="background: #FFC82B; color: #1B1C1F; font-weight: 700; padding: 2px 10px; border-radius: 12px; font-size: 13px;">' + r.count + '</span>';
html += '</div>';
if (r.status === 'error') {
html += '<div style="color: #c33; font-size: 13px;">Error: ' + r.error + '</div>';
} else if (r.samples && r.samples.length > 0) {
html += '<div style="font-size: 12px; color: #8F9194; margin-top: 8px;">Examples:</div>';
r.samples.forEach(function(s) {
const subj = (s.subject || '(no subject)').substring(0, 80);
const from = s.from.replace(/<.*>/, '').trim().substring(0, 40);
html += '<div style="font-size: 13px; color: #434446; padding: 4px 0; border-top: 1px solid #F6F7FB; margin-top: 4px;">';
html += '<div style="font-weight: 500;">' + escapeHtml_(subj) + '</div>';
html += '<div style="color: #8F9194; font-size: 12px;">' + escapeHtml_(from) + '</div>';
html += '</div>';
});
}
html += '</div>';
});
html += '<div style="text-align: center; color: #8F9194; font-size: 12px; margin-top: 24px;">';
html += 'Gmail Auto-Cleanup by <a href="https://o-cmo.com" style="color: #8F9194;">O-CMO</a>';
html += '</div>';
html += '</div>';
html += '</div>';
GmailApp.sendEmail(
email,
prefix + 'Gmail Cleanup: ' + results.totalProcessed + ' emails',
'Your email client does not support HTML. Total: ' + results.totalProcessed,
{ htmlBody: html }
);
}
function sendTelegramReport_(results) {
const prefix = results.isDryRun ? '[DRY RUN] ' : '';
let msg = '*' + prefix + 'Gmail Cleanup*\n';
msg += '_' + results.timestamp.toLocaleString() + '_\n\n';
msg += '*Total:* ' + results.totalProcessed + ' emails\n\n';
results.rules.forEach(function(r) {
if (r.count > 0) {
msg += '- ' + r.label + ': *' + r.count + '*\n';
}
});
const errors = results.rules.filter(function(r) { return r.status === 'error'; });
if (errors.length > 0) {
msg += '\n*Errors:*\n';
errors.forEach(function(r) { msg += '- ' + r.label + ': ' + r.error + '\n'; });
}
sendTelegram_(msg);
}
function sendTelegram_(text) {
try {
const url = 'https://api.telegram.org/bot' + CONFIG.TELEGRAM_BOT_TOKEN + '/sendMessage';
const response = UrlFetchApp.fetch(url, {
method: 'post',
payload: {
chat_id: CONFIG.TELEGRAM_CHAT_ID,
text: text,
parse_mode: 'Markdown'
},
muteHttpExceptions: true
});
const code = response.getResponseCode();
if (code !== 200) {
Logger.log('Telegram error: ' + code + ' — ' + response.getContentText());
return false;
}
return true;
} catch (e) {
Logger.log('Telegram exception: ' + e.message);
return false;
}
}
function logToSheet_(results) {
try {
const sheet = getOrCreateLogSheet_();
results.rules.forEach(function(r) {
if (r.count === 0) return;
const sampleSubjects = r.samples.map(function(s) { return s.subject; }).join(' | ');
sheet.appendRow([
results.timestamp,
results.isDryRun ? 'DRY_RUN' : CONFIG.ACTION,
r.label,
r.count,
r.query,
sampleSubjects
]);
});
} catch (e) {
Logger.log('Sheet log error: ' + e.message);
}
}
function getOrCreateLogSheet_() {
const props = PropertiesService.getScriptProperties();
let sheetId = props.getProperty('LOG_SHEET_ID');
let ss;
if (sheetId) {
try { ss = SpreadsheetApp.openById(sheetId); } catch (e) { sheetId = null; }
}
if (!sheetId) {
ss = SpreadsheetApp.create(CONFIG.SHEET_NAME);
const sheet = ss.getActiveSheet();
sheet.appendRow(['Timestamp', 'Action', 'Rule', 'Count', 'Query', 'Sample Subjects']);
sheet.getRange(1, 1, 1, 6).setFontWeight('bold').setBackground('#FFC82B');
sheet.setFrozenRows(1);
props.setProperty('LOG_SHEET_ID', ss.getId());
Logger.log('Created log sheet: ' + ss.getUrl());
}
return ss.getActiveSheet();
}
function escapeHtml_(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
// ============================================================
// TELEGRAM SETUP (follow these steps once)
// ============================================================
//
// 1. Open Telegram, find @BotFather, send /newbot
// 2. Choose a name (e.g. "My Gmail Cleanup Bot") and username (must end in "bot")
// 3. BotFather will give you a TOKEN like: 7894561230:ABCdefGhIJklmNOpQrsTuVwxyz
// Paste it into CONFIG.TELEGRAM_BOT_TOKEN above
// 4. Send any message to your new bot (e.g. "hi")
// 5. Open this URL in browser (replace <TOKEN> with your token):
// https://api.telegram.org/bot<TOKEN>/getUpdates
// 6. Find "chat":{"id": ... } — copy the number
// Paste it into CONFIG.TELEGRAM_CHAT_ID above
// 7. Set CONFIG.SEND_TELEGRAM = true
// 8. Run testTelegram() function to verify it works
//
// Done! You'll get a Telegram message after every cleanup run.