I have a Gmail filter that applies a label ('OTPs') to certain incoming messages. They accumulate and I want to keep most for only a couple of days.

I can eliminate them manually by performing a search (e.g. 'older_than:2d label:OTPs -label:GST') and then deleting the results, but I want to automate this process using a filter.

The example below shows a highlighted message thread 'SMS Forwarder' that totals 21 individual messages of which only 7 would match my criteria for deletion, and the remaining 14 would be kept.

enter image description here

  • So, all the messages get forwarded to mail box including OTPs. Now there are 1000s of OTPs sitting there in my mail, which are basically useless now. So, I want to delete them. Now problem with Gmail is, that the filters would work ONLY for the incoming mails, not the existing ones. I want to clear up my inbox by deleting any mail containing the keyword(s) - "OTP" or "One Time Password", including a single mail in a conversation thread. What is the best way to do it? Dec 6, 2021 at 10:20
  • I noticed that you excluded the label GST in your search example in your original post. Are there other labels that will be excluded? Dec 7, 2021 at 3:52

2 Answers 2


I wrote a Google Apps script that archives threads with labels matching particular patterns: Gmail-archive-after-script. I've been using it for a couple of years now and couldn't bear my inbox without it.

I have not, however, done any testing on what I can do with individual messages in threads, and I'm too much of a coward to actually delete messages automatically.


Gmail only applies filters to incoming messages. If you want to automate the process, you can use a Google Apps Script.

I have created a script that can be used to delete individual messages based on a custom label that can be manually added or added via a Gmail filter. For example, a message labeled 'delete.in.3.days' would cause a message to be moved to TRASH if at least 3 days old.

I posted the code and installation instructions on Github at GAS-Gmail-Trash-by-Expiry-Label. The script has a Test Mode that allows it to be run without actually making any changes.

The code is long but includes a lot of logging which I prefer.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.