r/GoogleAppsScript • u/VAer1 • 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
View all comments
Show parent comment
1
u/stellar_cellar Jul 26 '25
So when you append a thread to the array threadsToTrash, you giving a reference to the thread object that was being work during that loop iteration. That reference won't change when you use getThreads() again; the indexing change won't affect it.
Let's say Thread A is at index 0 (newest message) in Gmail, so when you retrieve it, you get an object (instance of class GmailThread) that contains all the properties of Thread A; if you save that object to a variable (e.g. Array), it will always contain Thread A properties until you assign a new value to that specific variable. So if Thread B comes in takes position at index 0 in Gmail and you do getThreads(), it will not overwrite the variable where you saved Thread A unless you explicit tell it to do it.
Finally when you do the moveThreadsToTrash(), it uses the object reference/properties saved in each element of the array to determine which threads to actual execute on.