Small Business Stack

Label and Archive Old Newsletters in Gmail with Apps Script

How can I automatically label and archive old newsletters and promotions in Gmail without deleting them?

Paste the script into a standalone Apps Script project, leave DRY_RUN set to true and run it once to see how many threads match. When the count and sample subjects look right, set DRY_RUN to false. Each run labels and archives up to 500 matching threads, 100 at a time, and never deletes anything. Add the daily trigger to keep the inbox clear.

What you need

  • A Gmail account with inbox categories turned on, so category:promotions has something to match
  • A standalone Apps Script project owned by the same account
  • Permission to let the script read and change Gmail (the https://mail.google.com/ scope)

How this script runs

  1. A daily trigger starts the script
  2. It searches for promotions older than 30 days that are not starred or archived
  3. In dry-run mode it logs a count and sample subjects, then stops
  4. Otherwise it labels up to 100 threads per batch
  5. It archives the same threads and repeats up to 5 batches

A short Apps Script can move old newsletters out of a Gmail inbox every day without deleting any of them. It searches for promotions older than 30 days, puts a label on each conversation so you can find them again, and archives them. The first run is a dry run: it only counts what matches and logs a few subjects, so you can check the search before anything moves.

This suits a founder or office manager whose inbox fills with supplier offers, software newsletters and event mail. The mail stays in the account under one label, which makes it easy to check later or delete by hand once you trust the filter.

What the script searches for and why

The search is the same text you would type into the Gmail search box:

category:promotions older_than:30d -is:starred -in:archive

Each part comes from Google’s list of Gmail search operators:

Part Effect
category:promotions Mail Gmail sorted into the Promotions category
older_than:30d Older than 30 days; units are d, m or y
-is:starred Leaves out starred mail
-in:archive Leaves out mail that is already archived, so each run moves on to new threads

Google describes category: as working “if you use inbox categories”. If your inbox has categories turned off, test the search in Gmail first. If it returns nothing, the script will do nothing either.

Unsubscribe headers are not used here. Google’s operator page lists list: for mail from a mailing list and a general header: operator, but it does not document searching for an unsubscribe header, so this guide sticks to the category. If one newsletter keeps landing in your Primary tab, change the query to something like list:news@example.com older_than:30d -is:starred -in:archive, using the list address from one of its messages.

The -is:starred term has a catch that Google’s page spells out. Negative operators match messages, not whole conversations, so a conversation can still match if one of its messages is unstarred. For newsletters this rarely matters, because they are almost always single-message threads.

The complete Apps Script

Create a standalone project at script.google.com, signed in as the mailbox owner, and replace the starter code with this:

const DRY_RUN = true;
const SEARCH_QUERY = 'category:promotions older_than:30d -is:starred -in:archive';
const LABEL_NAME = 'Old newsletters';
const BATCH_SIZE = 100;
const MAX_BATCHES_PER_RUN = 5;

function archiveOldNewsletters() {
  if (DRY_RUN) {
    countMatchingThreads();
    return;
  }

  const label = GmailApp.getUserLabelByName(LABEL_NAME) ||
    GmailApp.createLabel(LABEL_NAME);
  const seen = new Set();
  let archived = 0;

  for (let batch = 1; batch <= MAX_BATCHES_PER_RUN; batch++) {
    const threads = GmailApp.search(SEARCH_QUERY, 0, BATCH_SIZE)
      .filter(thread => !seen.has(thread.getId()));

    if (threads.length === 0) {
      break;
    }

    threads.forEach(thread => seen.add(thread.getId()));
    label.addToThreads(threads);
    GmailApp.moveThreadsToArchive(threads);
    archived += threads.length;
    console.log('Batch ' + batch + ': labelled and archived ' +
      threads.length + ' threads.');
  }

  console.log('Finished. Labelled and archived ' + archived +
    ' threads this run. Nothing was deleted.');
}

function countMatchingThreads() {
  const limit = BATCH_SIZE * MAX_BATCHES_PER_RUN;
  let total = 0;

  for (let start = 0; start < limit; start += BATCH_SIZE) {
    const threads = GmailApp.search(SEARCH_QUERY, start, BATCH_SIZE);

    if (start === 0) {
      threads.slice(0, 10).forEach(thread => {
        console.log('Sample: ' + thread.getFirstMessageSubject() +
          ' | last message ' + thread.getLastMessageDate());
      });
    }

    total += threads.length;

    if (threads.length < BATCH_SIZE) {
      console.log('DRY RUN: ' + total + ' threads match. Nothing was changed.');
      return;
    }
  }

  console.log('DRY RUN: at least ' + total + ' threads match. A live run ' +
    'handles up to ' + limit + ' per run. Nothing was changed.');
}

function installDailyTrigger() {
  const handler = 'archiveOldNewsletters';

  ScriptApp.getProjectTriggers()
    .filter(trigger => trigger.getHandlerFunction() === handler)
    .forEach(trigger => ScriptApp.deleteTrigger(trigger));

  ScriptApp.newTrigger(handler)
    .timeBased()
    .atHour(6)
    .everyDays(1)
    .create();
}

The script calls only label and archive methods. There is no call to moveThreadsToTrash or any delete method, so a mistake in the search moves mail to an archive with a label on it, which you can undo.

Running the dry run, then switching it on

  1. Save the project and give it a name you will recognise later, such as “Newsletter archiver”.
  2. Run archiveOldNewsletters with DRY_RUN still true. Apps Script asks for permission the first time. Google’s GmailApp reference lists https://mail.google.com/ as the scope for these methods, which is full Gmail access, so read the prompt and make sure the account shown is the right one.
  3. Read the execution log. It shows up to 10 sample subjects and a count, for example DRY RUN: 342 threads match. Nothing was changed. If an invoice, booking or order confirmation appears among the samples, tighten the search before going further.
  4. Set DRY_RUN to false, save, and run it once by hand. Each batch logs a line such as Batch 1: labelled and archived 100 threads.
  5. Check Gmail. The archived threads appear under the Old newsletters label and no longer show in the inbox.
  6. Run installDailyTrigger once. Then look under Triggers in the project to confirm there is one entry for archiveOldNewsletters.

To undo a run, open the Old newsletters label in Gmail, select the threads and move them back to the inbox. The label stays on them until you remove it.

Why batches of 100 and a cap of 500 per run

Google’s GmailLabel reference says addToThreads handles “up to 100 threads per batch”. The script asks GmailApp.search for at most 100 threads at a time and passes the same group to moveThreadsToArchive, so neither call goes over that number. The GmailApp reference also warns that a search with no range “will fail when the size of all threads is too large”, and recommends the paged form search(query, start, max), which is what the script uses.

The live run always searches from position 0. Archived threads drop out of the results because of -in:archive, so the next batch picks up new threads. If Gmail’s search has not caught up yet and returns the same threads again, the seen check filters them out and the run stops instead of looping.

The dry run cannot rely on that, since it changes nothing. It steps through results 100 at a time with the start value and stops at 500, the same cap as a live run.

The cap of 5 batches keeps each run short. Google’s Apps Script quotas page sets a 6-minute limit per execution and a daily limit on Gmail read and write calls. A first clean-up of thousands of threads will take several days at 500 a day. To go faster, run archiveOldNewsletters by hand a few times rather than raising the batch size.

Setting Default What changing it does
DRY_RUN true false lets the script label and archive
SEARCH_QUERY promotions older than 30 days Widen or narrow what counts as a newsletter
LABEL_NAME Old newsletters The label added before archiving; created if missing
BATCH_SIZE 100 Keep at 100 or lower to stay within the documented label limit
MAX_BATCHES_PER_RUN 5 Threads per run is this times BATCH_SIZE

Cases where a Gmail filter or manual clean-up works better

If you only want future newsletters to skip the inbox, a Gmail filter may be simpler. Google’s operator page notes that you can set up a filter from a search’s results. The script is more useful for mail that is already sitting in the inbox and needs to age out on a schedule.

Avoid this script when:

  • The inbox is shared or delegated. Archiving changes what everyone sees. Agree on the rule first.
  • Order confirmations and receipts land in Promotions. Gmail’s sorting is not perfect. Run the dry run, read the samples, and add -from: terms for senders you need to keep in view.
  • Storage is the real problem. Archived mail stays in the account and still uses storage, so this does nothing for a full mailbox.

For other scheduled Apps Script jobs, compare creating Gmail reply drafts from Google Forms responses and posting a daily blocked-tasks summary to Slack. More guides on everyday company tools are under the small business stack topic.

Sources

Free, from Producfy

Get the next guide before you need it

One email when a new guide or tool goes up: working formulas, queries and scripts for spreadsheets, SQL and the CRM and billing exports that end up in them. At most one a week.

Esc