How to Send Email from mailx Command in Linux Using Gmail’s SMTP introduces how to send email using heirloom mailx (or s-nail if you are using Ubuntu 18 or later or similar releases) command in Linux through Gmail’s SMTP which requires some configuration. On the other hand, there are many environments that do not require SSL/TLS/etc. One example is the SMTP server (smtp.ust.hk) for HKUST requires no authentication for sending email from IPs inside the campus network. In this tutorial, I will introduce how to send email using mailx through internal SMTP (using HKUST’s smtp server smtp.ust.hk as the example).
There are at least two methods: using all-in-one command or putting configurations into profile. The all-in-one-command way needs no other configurations except the command line itself, while the way using configuration has a clearer command.
This is an all-in-one command that sends email to $TO_EMAIL_ADDRESS . You need to also replace these $FROM_EMAIL_ADDRESS and $FRIENDLY_NAME variables with your email and name.
s-nail instead in releases without the heirloom mailx)
$ mailx -v -s "$EMAIL_SUBJECT" -S smtp=smtp://smtp.ust.hk -S from="$FROM_EMAIL_ADDRESS($FRIENDLY_NAME)" $TO_EMAIL_ADDRESS
mailx will read the email content from STDIN. Type in the email main content and input "Ctrl+d" to tell mailx you have finished the content. The mail will be sent out. You can also use pipes like:
$ echo "The mail content" | mailx -v -s ...
Using configuration file
If you use this configuration frequently, you man consider putting the configuration into
mailx‘s configuration file
set smtp=smtp://smtp.ust.hk set from="$FROM_EMAIL_ADDRESS($FRIENDLY_NAME)"
Then you can send email directly by:
$ mailx -v -s "$EMAIL_SUBJECT" $TO_EMAIL_ADDRESS