splitbrain.org

electronic brain surgery since 2001

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 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.

Tags:
appscript, gmail, automation, javascript
Similar posts:

Comments