How to Send Email Using mailx/s-nail in Linux Through Internal SMTP

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.

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

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

10 comments:

  1. 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

  2. Pingback: Linux Sunucuya SSH Bağlantı Sonrası Uyarı Postası Gönderme | Fatih ASLAN | ITPro Blog
  3. 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.

  4. 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!

Leave a Reply

Your email address will not be published. Required fields are marked *