Wednesday, January 30, 2013

Sending E-mails from Command-Line Easily

On the presupposition that most people have no interest in running an e-mail server for sending/receiving e-mails but probably wouldn't mind being able to send e-mails easily from the command-line, let's set up a way to use a public mail service like Gmail.

First of all, you'll need mailutils, which is probably installed, but if not:
# apt-get install mailutils

From this point forward, there are a lot of choices, and they all seem to do more or less the same thing, so I've chosen ssmtp.
# apt-get install ssmtp



As root, add the following to /etc/ssmtp/ssmtp.conf:

AuthUser=EMAIL@gmail.com
AuthPass=PASSWORD
mailhub=smtp.gmail.com:587
UseSTARTTLS=YES


and uncomment/add the line (which may or may not be useful, but I noticed that I've done that):

FromLineOverride=YES

If not using Gmail, you're going to have to figure out the SMTP server address yourself. Depending on what you choose to do this for, you may also want to create a separate account for such purposes. For example, I've given my Raspberry Pi its own Gmail account, which occasionally sends my account e-mails about stuff.

The way sending mail works is that the user uses the mail command, which in turn calls the sendmail command, which should be a symlink to ssmtp. Make sure this is the case:

$ whereis sendmail
sendmail: /usr/sbin/sendmail /usr/lib/sendmail /usr/share/man/man8/sendmail.8.gz

$ ls -l /usr/sbin/sendmail
lrwxrwxrwx 1 root root 5 Jul 10  2012 /usr/sbin/sendmail -> ssmtp


If not, change it so that it is (by hand or with update-alternatives or similar).

At this point, everything should just work:

$ echo "Hello, World!" | mail -s "Test Subject Line" whoever@email.com

I use this within scripts/cron jobs for when things go wrong, and I should be informed.

No comments:

Post a Comment