Archive Gmail Threads by Label
Here's a simple time-based script that will check for threads with any of the labels in the array labelNames. For example, Followup and Hold.
If any threads are found with those labels, it will archive them if any are in the Inbox after first reapplying the label to ensure all messages in the thread are properly labeled.
The script will work whether conversation mode is on or off.
It should be noted that the script is written with the expectation that there won't be thousands of threads with those label names.
Main Script
// Archives Gmail threads by label and reapplies label // to thread at the same time. const labelNames = [ "Followup", "Hold" ]; function archiveGmailThreadsByLabel() { for (let i = 0; i < labelNames.length; i++) { let name = labelNames[i]; let label = GmailApp.getUserLabelByName(name); if (label) { let threads = label.getThreads(); let len = threads.length; let counter = 0; for (let i = 0; i < len; i++) { let thread = threads[i]; if (thread.isInInbox()) { counter += 1; thread.addLabel(label); thread.moveToArchive(); } } console.log("\""+name+"\" ["+len+" Thread"+(len == 1?"":"s")+ (len ? "; "+ counter +" Archived]" :"]")); } else { console.log("\""+name+"\" [**Label doesn't exist**]")} } }
Time-Based Trigger Script
You need to manually install a time-based trigger or you can add the additional code below to the existing script and then install the trigger by running the install_trigger function from the script editor.
The schedule is currently set to 5 minutes using everyMinutes(5). Valid values for everyMinutes() are 1, 5, 10, 15, 30. See Class ClockTriggerBuilder for other time-based options.
function install_trigger(){ delete_triggers() // avoids duplicates ScriptApp.newTrigger("archiveGmailThreadsByLabel").timeBased().everyMinutes(5).create(); } function delete_triggers(){ ScriptApp.getProjectTriggers().forEach(t => ScriptApp.deleteTrigger(t)); }
