How to Send Email Using mailx/s-nail in Linux Through Internal SMTP
Posted on In LinuxHow 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.
All-in-one 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.
(use 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 ~/.mailrc
.
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
Thanks. This helped me a lot
syntax for attachemnt for sending mail via mailx with smtp please…
$ mailx -v -s "$EMAIL_SUBJECT"
-S smtp=smtp://smtp.ust.hk
-S from="$FROM_EMAIL_ADDRESS($FRIENDLY_NAME)"
-a /path/to/attachment/files
$TO_EMAIL_ADDRESS
Check more options available in `mailx` manual: https://www.systutorials.com/docs/linux/man/1-heirloom-mailx/
worked fine …
with
mailx -v -s “$EMAIL_SUBJECT” \
-S smtp=smtp://smtp.ust.hk \
-S from=”$FROM_EMAIL_ADDRESS($FRIENDLY_NAME)” \
-a /path/to/attachment/files \
$TO_EMAIL_ADDRESS
Thank you very much!! Could you please help me with a question:
“consider putting the configuration into mailx‘s configuration file ~/.mailrc”
sounds like this file exists already? Is that right? I couldn’t find the file at my Ubuntu.
Hi Lisa, you can create that file if it does not exist yet.
Thank you very much!!
Hi! Thanks for this information. Do you know if I can send through multiple SMTP servers by simply adding more “-S smtp=” lines? I want to have some failover.
Thanks!
I am not aware of such functionalities of any `mailx`. A small script might achieve that though.