Thursday, July 19, 2012

Sending emails from Linux command line (bash)


I have built an automated system that pulls information from the web, analyzes it and puts the results of that analysis on a big monitor. I wanted to add to that some sort of an alert system so that when a specific event occurs, it will send me an email alerting me about the situation.

It’s mostly written in bash running on Linux, so I used mutt to do the email part.

To install mutt (I used a Ubuntu based distro), run the following as root:
apt-get install mutt

Configuring
For the email client to work properly, you need to configure a few parameters. You do that through creating and editing ~/.muttrc (using any text editor such as vi).

set from = “name@domain.com”    # the email address the email
                                # will appear to be coming from
set realname = “Amir Harush”    # the name that will appear as
                                # “from” in the recipient email
                                # client
set envelope_from=yes           # see below

The last line deserves some explanation. The protocol used to send emails in the internet is called SMTP. When sending an email, there are two parts that get involved: the email itself (which is what you see in an editor such as Outlook or Gmail) – which contains the subject, the body, recipients, etc. It also contains the from (your email address). This setting is the "from" setting in the configuration file (first line). Consider the email itself as the paper on which you write your letter (and also add the recipients, subjects, etc. to).

The other part that SMTP needs is the actual information that is needed to route the email to its intended recipients (TO, CC or BCC). It also needs information about who is sending the email. Continuing the previous analogy of paper, this part would be the envelope.

By default, mutt uses your computer’s domain and username to determine who is sending the email. In my case, it was ‘root@localhost’. Many mail servers will reject this address:
Diagnostic-Code: smtp; 573 root@localhost failed to route the address

To solve this, I had to add the last line to tell mutt to use the same address configured in ‘from’ for the envelope's ‘from’. That allowed my email server to accept the address as valid and allow the email to proceed to its intended recipient (me).

That’s it. Everything is now ready to send an email:
cat file_with_text.txt | mutt -s “Analysis Results” name@domain.com

You can also send attachments using the -a option. Run ‘man mutt’ for information on how to use mutt or go here.