Wednesday, July 22, 2009

Send email from a Linux shell

Most of us only send email to other people and use either a desktop client or some form of webmail. For those who are so inclined, sending an email from the command line in Linux is also relatively easy. First, you will need to install ssmtp. In Ubuntu, run this command:
sudo aptitude install ssmtp
If you are using a different distribution it may exist in your repositories already or you may have to add a new one. You will need to make some changes to the default config file. Make a backup of the original file in case you want to revert back to it:
sudo cp /etc/ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf.orig
When I set this up, I created a Gmail account so that I could keep track of the emails sent conveniently if I want. To set it up to use a Gmail account, edit the config file so that these lines are present:
root=[your address]
AuthUser=[your address]
Now any message you send will come from [your address] and you can see what messages have been sent by logging into that Gmail account. This is the easiest way I have found to send a message:
echo -e "Subject: [some subject]\n\n[the body goes here]\n[second line of body]\n" | ssmtp [address to send to]
So, for example, to send a message with a subject of "This weekend" and a body of "Want to get dinner friday? Call me." to, you would type this:
echo -e "Subject: This weekend\n\nWant to get dinner friday? Call me.\n" | ssmtp
The -e flag on echo tells it to look for backslash escape characters. This means that everywhere there is a "\n" it will become a new line. Also, notice that there is an extra line between the subject and the body.

So why is this useful? This is useful to send yourself notifications from the system. For example, you might have a cron script that runs every so often and you want a notification whenever it finishes successfully. Another example I saw during my research was to add a line to "/root/.bashrc". That will send out a message whenever someone logs in as root to the system.

You can also have it send text messages to your phone. To do so, just send an email to the corresponding address for the service provider:


  1. Why wouldn't I just use the 'mail' command?
    For example,
    echo “Body of the message here.” | mail -s “subject"

  2. Phil,

    Always catching things that I miss! Yes, "mail" works, it just requires installing it for some systems. Ubuntu, for example, does not have the "mail" program installed automatically. CentOS does though.

  3. Can you tell me how I should escape special characters like apostrophes and space characters in the authpass field? I can get the authentication to happen when I remove these characters from my mail server password but I'd much rather include them. I have tried backslash, enclosing in quotes in various combinations but nothing seems to work...


Note: Only a member of this blog may post a comment.