r/GoogleAppsScript • • Jul 26 '25

Question Delete old gmail threads within a label (exclude Sent and Starred)

Could someone help me fix the code?

I have quite some threads (oldest is 12/11/2023, not in Sent folder, not starred) meeting the deletion requirement, but the code does not delete any of those old threads.

What is wrong with the code?

Edit: I added two screenshots, for debug variables, not sure why Array size for threads is only 500, not 4314. It seems the code can only read first 5 pages of gmail thread (there is limit 500?). Not sure why label does not have value

function deleteOldThreadsExcludeSentAndStarred() {

  const labelNames = ["Finance & Bill", "RTest"];
  const labelSet = new Set(labelNames);
  const now = new Date();
  const batchSize = 100;
  const maxToDelete = 5000; // safety cap per run

  const daysOld = 530;
  const msPerDay = 1000 * 60 * 60 * 24;  //1000 (ms) × 60 (s) × 60 (min) × 24 (hr) = 86,400,000 milliseconds/day


  for (let labelName of labelSet) {
    
    
    var label = GmailApp.getUserLabelByName(labelName);
    if (!label) {
      Logger.log("Label not found: " + labelName);
      return;
    }

    const threads = label.getThreads();
    const threadsToTrash = [];

    for (let i = 0; i < threads.length && threadsToTrash.length < maxToDelete; i++) {
      const thread = threads[i];
      const ageInDays = (now - thread.getLastMessageDate()) / msPerDay;

      if (ageInDays > daysOld) {
        const labels = thread.getLabels().map(l => l.getName());
        const isStarred = labels.includes("STARRED");
        const isSent = labels.includes("SENT");

        if (!isStarred && !isSent) {
          threadsToTrash.push(thread);
        }
      }
    }

    // Batch delete
    for (let i = 0; i < threadsToTrash.length; i += batchSize) {
      const batch = threadsToTrash.slice(i, i + batchSize);
      GmailApp.moveThreadsToTrash(batch);
      Utilities.sleep(1000); // slight delay to avoid rate limits
    }

    Logger.log(`Moved ${threadsToTrash.length} threads to Trash from label: "${labelName}".`);

  }



}
1 Upvotes

64 comments sorted by

View all comments

Show parent comment

1

u/stellar_cellar Jul 26 '25

const threads = GmailApp.search(`label:${gmailLabels[i]} is:unstarred -in:sent`);

If you the ` characters (located below the escape key) instead of quotes, you can use the ${} parameters to insert variable value into a string.

If you use " or ', you can concatenate variable to string using + (example: "I have " + 5 + " apples")

1

u/VAer1 Jul 26 '25 edited Jul 26 '25

Is below code structure correct? Or does it work?

particularly the line of code in For statement, is it correct?

I would like to check no more than 100 threads in each label, per run. In order to reduce program execution time per run, otherwise, it may already exceed time limit before deleting any threads.

      const query = `label:${gmailLabel} -in:sent -is:starred`;      
      const threads = GmailApp.search(query);  //isStarred and isSent in below commented code do not really work correctly, so to exclude them from variable threads, by using search function
      //const threads = GmailApp.search(label:${gmailLabels[i]} is:unstarred -in:sent);  //Alternative, has not tested yet

      if (threads.length === 0) break;  //stop looping, but the function keeps running after the loop

      if (threads.length > 100) {
        var numberOfThreadsToCheck = 100;
      }
      else {
        var numberOfThreadsToCheck = threads.length;
      }

      var endIndex = threads.length - numberOfThreadsToCheck; //this thread will be checked last in the loop. E.g. if there are only 50 threads in the label, threads.length = 50, it will check threads from index 49 to index 0

      for (let j = threads.length -1; j >= endIndex; j--) {

      }

1

u/stellar_cellar Jul 26 '25

Looks good. Word of advice, avoid using var when declaring variables, use let instead.

2

u/VAer1 Jul 26 '25

Thanks. I will test the program later, and see if it runs correctly or if there are more issues. At the meanwhile, I would like to write another small program to record the number of threads in each label, and get the result to google sheet, on daily basis. so that I can compare the difference.

It is easier to notice the change within google sheet, just in case the code does not run correctly and mistakenly delete some threads in Sent or Starred.

1

u/stellar_cellar Jul 26 '25

you should add the "-in:trash" in the search parameters, so the deleted one are not included.

1

u/VAer1 Jul 26 '25

Thanks. I will add it now, totally forget threads in trash which could match the label.

1

u/VAer1 Jul 26 '25
if (threads.length > 100) {
        let numberOfThreadsToCheck = 100;  //prefer let than var
      }
      else {
        let numberOfThreadsToCheck = threads.length;
      }

In this case, I use let to declare numberOfThreadsToCheck, which gray out the variable numberOfThreadsToCheck.

In this case, how to avoid variable being grayed out?

Should I declare let numberOfThreadsToCheck; outside?

1

u/stellar_cellar Jul 26 '25

Declare you variable outside the IF block, the line above it. var can be accessed from anywhere in the script while let is limited by scope (var run the risk of being overwritten by accident by a different function).

1

u/stellar_cellar Jul 26 '25
//Here is a sample code with a 5 minutes timer, if you want to avoid the 6 minutes time out failure.function deleteOldThreadsExcludeSentAndStarred(){
  const startTime = Date.now();
  const gmailLabels = ["Finance & Bill", "Shipping Carriers (USPS)"];
  const batchSize = 500;
  for (let gmailLabel of gmailLabels){
    console.log(`Process started for ${gmailLabel}`)
    if (cleanThreads(gmailLabel, 0, batchSize, startTime)){
      console.log("5 minutes time limit reached.");
      break;
    };
    console.log(`Process completed for ${gmailLabel}`)
  }
  console.log("End of execution.")
}

function cleanThreads(gmailLabel, start, max, startTime){
  if (timeLimit(startTime)){
    return true;
  }
  let trashThreads = [];
  const threads = GmailApp.search(`label:"${gmailLabel}" -is:starred -in:{sent,trash} older_than:2d`, start, max); //Quotation around the label allows for the use of label with spaces in them. Older than is set to 2 days, can be adjusted
  for (let thread of threads){
    trashThreads.push(thread);
  }
  if (trashThreads.length > 0){
    GmailApp.moveThreadsToTrash(trashThreads);
  }
  console.log(`${trashThreads.length} moved to trash`);
  start = (start + max) - trashThreads.length;
  if (threads.length < max){
    return false;
  }
  return cleanThreads(gmailLabel, start, max, startTime);
}

function timeLimit(startTime){
  return (Date.now() - startTime) > 300000;
}

1

u/VAer1 Jul 26 '25 edited Jul 26 '25

Thank you very very much for your time, I will take a look at the code tomorrow.

I will continue on this project in 24 hours, my other program tracking thread count within each label has invoked too many times of service, not sure which part of code is limited by Google. I want the program to be running while testing this program too. I have run this program much more times that the other program (thread count by label) today, and no issue with this program so far.

Already spend a lot of time on this project today, if I don't have time to finish it this weekend, maybe next weekend. There are still something not running correctly, not deleting anything, while I am sure there are quite some threads should be deleted based on array daysOld values.

Thanks again. I will work on this project at a later time. It takes much more time than I expect.

3:39:11 PM
Notice
Execution started


3:39:11 PM
Info
Moved 0 threads to Trash from label: "Finance & Bill".


3:39:11 PM
Info
Moved 0 threads to Trash from label: "Shipping Carriers (USPS)".


3:39:11 PM
Info
Gmail label not found: RTest


3:39:12 PM
Notice
Execution completed

1

u/VAer1 Jul 26 '25

for (let j = threads.length -1; j >= endIndex; j--)

  1. I am not sure if threads.length is limited by 500, if yes, I need more code to get the full count. I need to investigate this part of code when I am free, I suspect that it is also limited by 500, which causes not deleting old threads.
  2. If #1 needs to be changed, which means more code and more running time, I have trouble running it within 6 minutes, even if I want to check no more than 100 threads for each label. That being said, if #1 change is needed, I will need to completely rewrite the program, my next idea is --- the program will be triggered on hourly basis, if the hour is 0 (12am-1am), then only get a full count on labels index 0 and delete old threads in label index 0 (only checking oldest 100 threads for possible deletion); then if it is 1am-2am, then take care of label index 1; etc.....

I will move this standalone script file into Google Sheet. I will need more time to fix the code, which still does not run correctly. But I have invoked too many times of service within the Google Sheet, I will continue this project next week.

1

u/stellar_cellar Jul 26 '25

Array can be extremely large, like 4 billions elements big.

Calling on the Google Services is relatively slow, that's where your will get most of your optimization. For example, in your original code, you use getThreads(), then use getLastMessageDate() and getLabels() hundreds of time to find your specific threads; each of this call takes time to access the Google Services. You might see a boost in run time if you use the search() function instead to directly get those threads.

1

u/VAer1 Jul 26 '25 edited Jul 26 '25

I will see later, but I have invoked too many times of service already.

Does below code take time? Is there alternative way to get the result? I may need to incorporate below code into #1 issue mentioned in above your post.

Below function is used to counted thread of all my labels, which is different script file, which takes more than 3 minutes. I cannot image how much more time needed if adding below code to this program. I may need to replace threads.length with below code, I doubt if threads.length returns correct value if there are more than 500 threads. Not sure, I will investigate.

I need to solve two issue (workaround): 6 minutes execution time limit; invoke too many times of service. Maybe invoke too many times of service is not an issue after finishing the project, I just test running too many times.

// Helper: accurately count threads in labels with >500 threads
function getFullThreadCount(label) {
  let count = 0;
  const batchSize = 100;
  let threads;

  do {
    threads = label.getThreads(count, batchSize);
    count += threads.length;
  } while (threads.length === batchSize);

  return count;
}

1

u/VAer1 Jul 26 '25

Does Calling on the Google Services during midnight (not busy hour) help save running time?

How to replace something with getLastMessageDate()?

1

u/stellar_cellar Jul 26 '25

Maybe you will get less busy server around midnight, I have no idea it can be random at times.

I did some bench marking, I can tell you the more threads you retrieve at once the better it is. getThreads(start,100) is faster than doing getThreads(start, 10) ten times.

Additionally, doing the getLastMessageDate() on each single thread is taking a toll; use the GmailApp.search("older_than:1d") instead. In my testing, to retrieve 88 threads ten times, it took 90 sec with getInboxthreads() and getLastMessageDate(), while with search() it only took 1 second. Use the code below for your own testing.

function getInbox(){
  let threads = []
  let startTime = Date.now();
  let iteration = 10;
  for (let i = 0; i < iteration; i++){
    let start = 0;
    const max = 100;
    let output = [];
    do {
      output = GmailApp.getInboxThreads(start, max);
      threads = threads.concat(output);
      threads.forEach(function(thread){thread.getLastMessageDate()});
      start += max;
    } while (output.length === max);
  }
  console.log("getInboxThreads: " + threads.length + " threads\n" + (Date.now() - startTime)/1000 +" seconds");

  threads = [];
  startTime = Date.now();
  for (let i = 0; i < iteration; i++){
    let start = 0;
    const max = 100;
    let output = [];
    do{
      output = GmailApp.search("in:inbox older_than:1d",start,max);
      threads = threads.concat(output);
      start += max;
    } while (output.length === max);
  }
  console.log("search: " + threads.length + " threads\n" + (Date.now() - startTime)/1000 +" seconds");
}

1

u/VAer1 Jul 27 '25

Thanks for the code, I will completely re-write the code for less running time. But I will test in 24 hours.

1

u/VAer1 Jul 27 '25

Is label.getThreadCount() valid method?

1

u/stellar_cellar Jul 27 '25

No, it's not a built in function.

1

u/VAer1 Jul 27 '25 edited Jul 27 '25

https://i.postimg.cc/9fkfs8Dn/Screenshot-2025-07-26-223755.png

How to correctly write the code?

Third line: syntax error.

First two lines: I debugged it, the array size of threads is 0. While there are threads in the label. There is no syntax error for these two lines, but it does not run correctly.

Edit with new screenshot: https://i.postimg.cc/8kY0sx3C/Screenshot-2025-07-26-232517.png

https://i.postimg.cc/vTD8hCLB/Screenshot-2025-07-26-233732.png

Edit: Never mind, I think the issue is related to label name, I should remove special characters from label name, it seems some special character does not work well in GmailApp.search

1

u/stellar_cellar Jul 27 '25

You are missing the ` around the query parameter (key below the escape key). Also the is:unstarred doesn't seem to work and combine the -in together. See below:

const threads = GmailApp.search(`label:"${gmailLabel}" -is:starred -in:{sent,trash}`);

1

u/VAer1 Jul 27 '25

By the way, Is:unstarred is not really what I want, I want to exclude threads which has at least one star . -is:starred is what I need.

 -is:starred 

"Is:unstarred" is a Gmail search operator that filters for emails that are not marked with a star. It's used in the search bar to display all conversations where at least one message is not starred, according to Gmail Help.