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
2
u/stellar_cellar Jul 26 '25
In the debug panel, label is an object so you have to click on the arrow to show it's properties.
If you look at the documentation for the getThreads(), it says that if the size of the threads is too large, the call may fail (could explain why you only getting 500 out 4000); the function does support using a "start" and "max" parameters, so try doing it in batch of 500:
https://developers.google.com/apps-script/reference/gmail/gmail-label#getThreads()