Deleting mail from a Linux users local account is easy using the mail command line utility. The mail command can also be used to perform any other functions that you can think of to manage email such as replying to messages, reading messages, or just sending messages. It is very basic in nature but it does provide a great utility for simple mail tasks.
Typically most of the mail that ends up in a user account on a Linux server that I might manage comes from a cronjob or some various task that is run on a server under a users name. It is important to understand and review these messages from time to time as they may have important information in them.
List Mail Messages: Summary List
- mail
List Mail Messages: More Details
- mail -N
List Mail Messages: For Another User
- mail -N -u username
Once you are in the mail interface you can quit at any time by just typing “q”.
Now to delete all mail from your user account type the below command from the CLI. You will not have a chance to retrieve these messages so make sure that it is something you want to do before proceeding.
Delete All Mail Messages:
- echo 'd *' | mail -N
Delete All Mail Messages: For Any User
- echo 'd *' | mail -N -u username
Another way to use the mail command from the Linux CLI is to get information from a server and email it to yourself or someone else. I find this very helpful when troubleshooting problems on a CentOS Linux server. For instance I may want to review a log file on another computer or have another systems administrator who may or may not have access to the server to view a log file. In the below example we will use the access.log file as an example Apache log that we want to email to ourselves so use the below command to do so.
- more apache.log | mail user@example.com
The above example will view the apache.log file using the more command and pipe it to the Linux CLI mail command to email the contents to user@example.com.
Those are just some basic examples of how to use the mail command so if you want more information you can always use the man command or view the manpage right here. The mail command has a lot of useful switches that can be integrated into the daily life of a systems administrator.