Search code examples
javascriptemailgoogle-apps-scriptgmail

Google Script for Gmail to Delete Emails With *Only* the Specified Label


I'm trying to find a way to target emails which have only one label. I want to delete messages which have a specific label and are older than 2 weeks. However, I want the script to ignore any emails which have additional labels besides the specified label.

For example an email with label 'Subscriptions' gets deleted, but an email with label 'Subscriptions' AND 'Keep!' will not.

The version I have currently will delete any email with the specified label regardless of any other labels applied.

I am using the publicly available Gmail Cleaning Robot script by Fred Mouniguet as my base.

Here's what I have so far:

function gmailCleaningRobot() {

var delayDays = 14; // will only impact emails more than 2 weeks old
var maxDate = new Date();
maxDate.setDate(maxDate.getDate()-delayDays); // what was the date at that time?

// Get all the threads labeled 'Subscriptions'
var label = GmailApp.getUserLabelByName("Subscriptions");
var threads = label.getThreads(0, 100);

// we archive all the threads if they're unread AND older than the limit we set in delayDays
for (var i = 0; i < threads.length; i++) {
if (threads[i].getLastMessageDate()<maxDate && threads[i].isUnread())
{
threads[i].moveToTrash();
}
}
}

Any help would be greatly appreciated!


Solution

  • You can solve this by using the getLabels on your thread instance in your if statement.

    try the following.

    if (threads[i].getLastMessageDate()<maxDate && threads[i].isUnread() 
        && threads.getLabels().length == 1)