Send Email from the Command Line using an External SMTP Server

Sending email in Linux is pretty straight forward, once an email server is set up. Just use mutt or mail and all is good. But sometimes you actually want to test if SMTP is working correctly. And not only on your box, but on a remote box. That is of course easy using a MUA like Thunderbird or Sylpheed, but that is not always feasible on a remote server in a remote network.

Luckily there is a solution to it using just the command line. To be precise, there are multiple solutions. Starting with SMTP by hand using telnet, but that is pretty hardcore. So how about mailx or swaks.

mailx

mailx is part of multiple packages, like mailutils, but I prefer the heirloom-mailx version. This version allows you specify a lot of SMTP connection details. Just check out the manpage. So on a Debian based distribution quickly install it with

apt-get install heirloom-mailx

An email can be sent with:

echo "Testbody" | mailx -v \
-r "me@example.com" \
-s "Test Subject" \
-S smtp="smtp.example.com:587" \
-S smtp-use-starttls \
-S smtp-auth=login \
-S smtp-auth-user="me@example.com" \
-S smtp-auth-password="changeme" \
-S ssl-verify=ignore \
memyselfandi@example.com

This would send an email to memyselfandi@example.com using the SMTP server smtp.example.com with STARTTLS, without verifying the SSL certificate. There are of course tons of other options. Just play around with it.

Swaks – Swiss Army Knife for SMTP

Swaks, the swiss army knife for SMTP, is a great little tool on the command line, that also offers an option to test SMTP servers. And it supports of course encryption using TLS.

Just install it with the packet manager of your distribution. Here is the Debian based version:

apt-get install swaks

And you can send an email with:

echo "This is the message body" | swaks \
--to "memyselfandi@example.com" \
--from "me@example.com" \
--server smtp.example.com \
--auth LOGIN \
--auth-user "me@example.com" \
--auth-password "changem" \
-tls

Yes, TLS is activate with a single dash parameter. Swaks, being a Perl script, can also just be downloaded from the Swaks homepage and works nicely in Cygwin.