Friday, April 12, 2013

Retrieve Linux local mailbox with command lines non-interactively

I need to automate reading email from Linux. So, I google to see if there is any available posted methods to do it in command line non-interactively. Surprisingly, there is no simple scripting method found. The web is either full of how to send email thru command line or how to read email interactively.

So, I dig into mail commands and I did some trials and errors. I discovered "echo" command can enter command to mail thru pipe. And combining with mail command, the command combinations will return the mail command output nicely to Linux stdout after each. Below are 6 handy command combinations.

1. Print all email to stdout
> echo "type *" | mail
> echo "type 1" | mail   # print the first email to stdout
> echo "type 3-5" | mail # print the emails from 3 to 5

2. Check if mail box is empty (i.e. "No mail for [username]" is found)
> echo q | mail 2>&1 | grep "No mail for [username]"

3. Purge the mail box
> echo "d *" | mail

> echo "d 3" | mail     # Delete the 3rd email

4. Save all emails in a text file
> echo "s * test.txt" | mail

5. Save emails between a range in a file
> echo "s 3-6 test.txt" | mail
This will save email from #3 to #6 to the file test.txt

6. Read one email from mailbox
> echo 1 | mail
Read the first mail from mail box
> echo 5 | mail
Read the 5th email from mail box
> echo 6 | mail
If there is no 6th mail from mail box. It will prompt you below error:
6: Invalid message number

The error message "Invalid message number" tells you that there is no 6th email in the mailbox. If the 5th email is successfully returned. You can treat the error message "Invalid message number" as end of mailbox just like the EOF of a file. Combined this with a loop, you can browse thru all the emails inside the mailbox. 

It was fun to dig those command combinations out. Just like resolving puzzles. :)

3 comments:

  1. You my friend, are a genius! I have been searching high and low for exactly this, and just like you, found innumerable posts to send or read interactively, but this! This is awe-freakin-some!!!

    ReplyDelete