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