Nat Taylor — Blog, AI, Product Management & Tinkering

Gmail Sweep Apps Script

Published on .

I consider many emails read after seeing the subject line, but then they sit in my Gmail inbox creating clutter. Outlook has “Sweep” to clear these out.

I made a google apps script that triggers once a day to “sweep” them out

Go to https://script.google.com/ to set up

Annoyingly, GmailApp.moveThreadsToArchive() does not return a value so we can’t know how many items were updates

function archiveOldInboxMessages() {
  // Corrected operator to target the actual inbox label
  var query = 'is:inbox -is:starred older_than:2d';
  var batchSize = 100;

  console.log(`Searching with query: "${query}" (limit: ${batchSize})...`);
  var threads = GmailApp.search(query, 0, batchSize);

  console.log(`Found ${threads.length} thread(s) matching criteria.`);

  if (threads.length === 0) {
    console.log('No eligible threads to archive.');
    return;
  }

  // Log a preview of the threads being modified
  // threads.forEach(function(thread, index) {
  //   var date = thread.getLastMessageDate().toISOString().split('T')[0];
  //   var subject = thread.getFirstMessageSubject() || '(No Subject)';
  //   console.log(`[${index + 1}/${threads.length}] ${date} - ${subject}`);
  // });

  try {
    GmailApp.moveThreadsToArchive(threads);
    console.log(`Successfully archived ${threads.length} thread(s).`);
  } catch (error) {
    console.error(`Failed to archive threads: ${error.message}`);
  }
}Code language: Python (python)

Post Navigation

«
»