Вход на сайт

Просмотр новости

Найдите то, что Вас интересует

Auto-Delete old Mails from GMail

Дата публикации: 08-03-2026 12:50:07


Auto-Delete old Mails from GMail
My inbox is a mess. While I manage to maintain a somewhat close to “Inbox Zero” at work, my personal GMail's inbox currently sits at 2,215 emails . A large amount of those mails are notifications of some kind, like from Github for example.
GMail has some mechanisms to automatically sort mails and I do make use of that, but those filters are applied when the mail arrives only.
For notifications I want to see the mail. So it should land in my inbox. But when I have ignored it for a certain time, it's pretty sure I don't need it anymore. So I wanted a way to automatically delete certain mail threads that are older than a specified number of days.
So here is what I came up with using Google Apps Script.
/**
* Main script to schedule
*
* Add one cleanEmails line per type of threads to clean
*/
function main() {
cleanEmails(true, '<notifications@github.com>', 7);
}
 
 
/**
* Find old thread based on given conditions
*
* @param {bool} clean Set to false to not actually delete the mails
* @param {string} searchString The string to search for
* @param {int} minAgeDays The minimum age a thread (newest message) has to have
* @param
*/
function cleanEmails(clean, searchString, minAgeDays, headerField = 'from') {
 
const threads = findRecentEmails(searchString, minAgeDays, headerField);
console.log(`Found ${threads.length} threads`);
 
threads.forEach((thread, i) => {
logThread(thread);
if(clean) {
thread.moveToTrash();
console.log('moved to Trash');
}
});
}
 
/**
* Log a thread to console
*
* @param {Thread} The gmail thread to log
*/
function logThread(thread) {
const firstMsg = thread.getMessages()[0]; // newest message in thread
const lastMsgDate = thread.getLastMessageDate();
const dateStr = Utilities.formatDate(
lastMsgDate,
Session.getScriptTimeZone(),
'yyyy-MM-dd HH:mm'
);
 
console.log(`Date: ${dateStr}, From: ${firstMsg.getFrom()}, Subject: ${thread.getFirstMessageSubject()}`);
}
 
/**
* Find old thread based on given conditions
*
* @param {string} searchString The string to search for
* @param {int} minAgeDays The minimum age a thread (newest message) has to have
* @param
*/
function findRecentEmails(searchString, minAgeDays, headerField = 'from') {
// Compute the cutoff date (messages must be older than this)
const cutoffDate = new Date(Date.now() - minAgeDays * 24 * 60 * 60 * 1000);
const cutoffFormatted = Utilities.formatDate(
cutoffDate,
Session.getScriptTimeZone(),
'yyyy/MM/dd'
);
 
// Build Gmail search query:
// - headerField:searchString → search in that header
// - before:YYYY/MM/DD → older than cutoff
// - -is:starred → skip starred
const query = `${headerField}:${searchString} before:${cutoffFormatted} -is:starred`;
console.log(`Query: ${query}`);
 
// get the 50 newest threads with their newest message older than the cut-off date
return GmailApp.search(query, 0, 75)
.filter(thread => thread.getLastMessageDate() < cutoffDate)
.sort((a, b) => b.getLastMessageDate() - a.getLastMessageDate())
.slice(0, 50);
}
The script is scheduled to run main() every hour. For now it only handles my Github notification mails, but more will follow. The cleanEmails() function takes four parameters:
clean: set it to false if you the method to run but not delete anything. The found threads will be printed to the console.
searchString: this is what identifies the threads to delete, for example the sender's email address
minAgeDays: defines how old the youngest message in the thread has to be to be considered for deletion
headerField: defaults to from but you sometimes might want to search the subject instead.
Each call to cleanEmails() will delete the newest 50 threads matching your criteria. And by delete I mean move them to the “Trash” folder – GMail will delete them automatically after 30 days. This adds a bit of safety if something goes wrong.
With the script running every hour it will take a while until all my old Github notifications are gone, but that's fine. I heard that GMail can become sluggish when deleting too many mails at once.
Tags: appscript, gmail, automation, javascriptSimilar posts:
Save Gmail Attachments to Google Drive
Gmail Backup and notmuch GUI
Password Hasher PWA
Add or read comments to this article »»Copyright © 2026 Andreas GohrThis feed is for personal, non commercial use in the subscriber's feedreader only.All contents (especially texts and images) are protected by copyright law and may not be republished outside of splitbrain.org without prior consent. Texts may be quoted in extracts under fair use policy. [digital fingerprint: sb97741286f601b4a0d496dc8bae242e6d]

Основное содержимое страницы с новостью.

My inbox is a mess. While I manage to maintain a somewhat close to “Inbox Zero” at work, my personal GMail's inbox currently sits at 2,215 emails 8-O. A large amount of those mails are notifications of some kind, like from Github for example.

GMail has some mechanisms to automatically sort mails and I do make use of that, but those filters are applied when the mail arrives only.

For notifications I want to see the mail. So it should land in my inbox. But when I have ignored it for a certain time, it's pretty sure I don't need it anymore. So I wanted a way to automatically delete certain mail threads that are older than a specified number of days.

So here is what I came up with using Google Apps Script.

/**
 * Main script to schedule
 *
 * Add one cleanEmails line per type of threads to clean
 */
function main() {
  cleanEmails(true, '<notifications@github.com>', 7);
}
 
 
/**
 * Find old thread based on given conditions
 * 
 * @param {bool} clean Set to false to not actually delete the mails
 * @param {string} searchString The string to search for
 * @param {int} minAgeDays The minimum age a thread (newest message) has to have
 * @param 
 */
function cleanEmails(clean, searchString, minAgeDays, headerField = 'from') {
 
  const threads = findRecentEmails(searchString, minAgeDays, headerField);
  console.log(`Found ${threads.length} threads`);
 
  threads.forEach((thread, i) => {
    logThread(thread);
    if(clean) {
      thread.moveToTrash();
      console.log('moved to Trash');
    }
  });
}
 
/**
 * Log a thread to console
 * 
 * @param {Thread} The gmail thread to log
 */
function logThread(thread) {
  const firstMsg = thread.getMessages()[0]; // newest message in thread
  const lastMsgDate = thread.getLastMessageDate();
  const dateStr = Utilities.formatDate(
    lastMsgDate,
    Session.getScriptTimeZone(),
    'yyyy-MM-dd HH:mm'
  );
 
  console.log(`Date: ${dateStr}, From: ${firstMsg.getFrom()}, Subject: ${thread.getFirstMessageSubject()}`);
}
 
/**
 * Find old thread based on given conditions
 * 
 * @param {string} searchString The string to search for
 * @param {int} minAgeDays The minimum age a thread (newest message) has to have
 * @param 
 */
function findRecentEmails(searchString, minAgeDays, headerField = 'from') {
  // Compute the cutoff date (messages must be older than this)
  const cutoffDate = new Date(Date.now() - minAgeDays * 24 * 60 * 60 * 1000);
  const cutoffFormatted = Utilities.formatDate(
    cutoffDate,
    Session.getScriptTimeZone(),
    'yyyy/MM/dd'
  );
 
  // Build Gmail search query:
  //   - headerField:searchString  → search in that header
  //   - before:YYYY/MM/DD         → older than cutoff
  //   - -is:starred               → skip starred
  const query = `${headerField}:${searchString} before:${cutoffFormatted} -is:starred`;
  console.log(`Query: ${query}`);
 
  // get the 50 newest threads with their newest message older than the cut-off date
  return GmailApp.search(query, 0, 75)
          .filter(thread => thread.getLastMessageDate() < cutoffDate)
          .sort((a, b) => b.getLastMessageDate() - a.getLastMessageDate())
          .slice(0, 50);
}

The script is scheduled to run main() every hour. For now it only handles my Github notification mails, but more will follow. The cleanEmails() function takes four parameters:

  1. clean: set it to false if you the method to run but not delete anything. The found threads will be printed to the console.

  2. searchString: this is what identifies the threads to delete, for example the sender's email address

  3. minAgeDays: defines how old the youngest message in the thread has to be to be considered for deletion

  4. headerField: defaults to from but you sometimes might want to search the subject instead.

Each call to cleanEmails() will delete the newest 50 threads matching your criteria. And by delete I mean move them to the “Trash” folder – GMail will delete them automatically after 30 days. This adds a bit of safety if something goes wrong.

With the script running every hour it will take a while until all my old Github notifications are gone, but that's fine. I heard that GMail can become sluggish when deleting too many mails at once.

Схожие новости

#Наименование новостиТональностьИнформативностьДата публикации
1Projects09.3223-03-2026
2Markdific - A better tool to open, read, edit and export Markdown files07.2305-10-2026
3Old Game, New Clothes07.8802-03-2026
4PocketCI - CircleCI in your pocket08.7929-09-2026
5Folo RSS Reader — Read timeline with Alfred08.5705-10-2026
6MD Studio - a personal HTML-to-Markdown project014.9605-09-2026
7EIP Editing Office Hour (EIP + ERC ) Meeting #113, Sep 15, 2026020.4607-09-2026
8Mail notification for Governor school email addresses05.4709-10-2026
9Daily Hacker News for 2026-09-2709.4328-09-2026
10Learn Claude Code and Cowork — Just $15 during Deal Days015.4804-10-2026

Классификация: . Схожих патентов: 0. Схожих новостей: 10. Тональность: 0. Информативность: 8.38. Источник: www.splitbrain.org.