Heirloom mailx for Quick Command-Line Email


email (Photo credit: Sean MacEntee)

If you manage Linux systems, you may need a quick way to send email from the command line. My recommended solution for simple scripted email is the Heirloom mailx utility. There are several reasons I like this tool. My favorite features are the quick ability to specify a remote SMTP server when sending, and the fact that popular distributions like RHEL, CentOS, Debian, and Ubuntu include supported packages for Heirloom mailx.

In RHEL 6.x and CentOS 6.x, install with "yum install mailx". In Ubuntu 12.04 LTS, install with "apt-get install heirloom-mailx".

Here is an example to send email with attachment to several email addresses. You can specify the from/return address, smtp server, subject, file attachment, and destination address(es).

echo "Test message body" | \
mailx -r '<ReturnAddress@Domain.Com>' -s 'Subject of Message' \
-a 'FileToAttach.txt' -S 'smtp=MailServer.Domain.com' \
'<Recipient1@Domain.com>' '<Recipient2@Domain.com>'
# Substitute real email addresses and a real smtp server.
# You can put it all on one line ...
# ... if you remove the "\" continuation markers.

In addition to sending email from your scripts, the Heirloom mailx tool can be very useful to test mail flow of email servers. It creates well-formed standards compliant mail messages quickly without the need for confusing and error-prone direct telnet smtp sessions. I hope you find this utility as useful as I do! 🙂

NOTE for RHEL 5.x and CentOS 5.x, you can install the supported package from the EPEL repository. The EPEL 5.x package name is “nail” for heirloom mailx (the 5.x command is also named “nail” – think of it as New mAIL).

BEWARE when attaching plain-text files, mailx may try to be smart and add an extra carriage return before every newline (even if your file already has them). If you’re having this problem, try either attaching only unix-formatted text files, or zipping up the file(s) before attaching.

About notesbytom

Keeping technology notes on WordPress.com to free up my mind to solve new problems rather than figuring out the same ones repeatedly :-).
This entry was posted in Linux, System Administration and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s