Send mail via SMTP servers
The default mail command on the Linux terminal, uses the local smtp server (mta) on port 25 to transmit emails. However at times you need to specify an external smtp server to use for sending mails.
For example you have just setup an smtp server, like Postfix or Exim, then you would want to test it out to check if it is receiving and relaying emails properly or not.
Being able to send mails from command line using this external smtp server is quick rather than having to setup a mail client like Thunderbird on your local machine.
1. mailx command
The mailx command is available from many different packages like mailutils, heirloom-mailx etc. We shall be using heirloom-mailx since it allows to specify smtp connection details in a single command and issue and email quickly.
$ sudo apt-get install heirloom-mailx
Now send an email with an external smtp server like this -
echo "This is the message body and contains the message" | mailx -v -r "[email protected]" -s "This is the subject" -S smtp="mail.example.com:587" -S smtp-use-starttls -S smtp-auth=login -S smtp-auth-user="[email protected]" -S smtp-auth-password="abc123" -S ssl-verify=ignore [email protected]
Here is a step by step version of the same command -
$ echo "This is the message body and contains the message" | mailx -v \ > -r "[email protected]" \ > -s "This is the subject" \ > -S smtp="mail.example.com:587" \ > -S smtp-use-starttls \ > -S smtp-auth=login \ > -S smtp-auth-user="[email protected]" \ > -S smtp-auth-password="abc123" \ > -S ssl-verify=ignore \ > [email protected]
Make sure to use the correct settings, like port number, authentication mechanism etc. The command would produce verbose output giving full details of the smtp communication that goes on behind, making it very easy to test and debug.
Check out the previous post on mailx command here -
9 mail/mailx command examples to send emails from command line on Linux
2. Swaks command
Swaks (Swiss army knife for SMTP) is a simple command line tool that can be used to test smtp servers to check if they are doing they job properly. It supports TLS as well.
Install swaks on Ubuntu/Debian with the following command
$ sudo apt-get install swaks
Now send the email
$ echo "This is the message body" | swaks --to [email protected] --from "[email protected]" --server mail.example.com --auth LOGIN --auth-user "[email protected]" --auth-password "abc123" -tls
All the options are pretty self explanatory. The "--server" option specifies the external SMTP server to use, "--auth" specifies the type of authentication. The "-tls" option tells swaks to use STARTTLS.
Check the man page for more options.