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