Need to delete mails for a range of dates in Linux

emailmail-command

I have 1 million mails generated in a Linux sever due to a cron job. I want to delete the mails, but not all as this cron mails useful to troubleshoot and find out the issue with cron job's execution. So I need to keep 1 month's mail and remove the remaining.

Best Answer

There are many different mail commands out there with different command sets. POSIX standardizes a mailx command.

Your mailbox will typically contain emails in the order in which they were received. So to delete older mails, you would typically delete lower-numbered emails. You can delete a range of messages with a command like d 1-42 (delete the first 42 messages).

If you want more control, I recommend Mutt, a command line email client that gives you a lot more control than the mail command. Mutt has a text mode interface and can also be scripted. In Mutt, you can use the command D to mark messages for deletion and enter the pattern ~d ->1m to select messages that are more than 1 month old. If you're satisfied with the list of messages to delete, type x to delete the messages marked for deletion.

Related Question