Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

Linux mail Command Usage with Examples

Send email from the command line or from scripts with the mail command.

Email2 min read3 steps

You can send email from a Linux server with the mail command, directly or from shell scripts.

How it works

When you send a message, mail calls the system sendmail program (/usr/sbin/sendmail). That program hands the message to the local Mail Transfer Agent (MTA), which delivers it over SMTP.

If you see an error such as send-mail: Cannot open mail:25, no MTA like Postfix is running on the server.

Install the mail command

The command comes from one of these packages:

  1. mailutils (GNU mailutils)
  2. heirloom-mailx / s-nail
  3. bsd-mailx

Their options differ a little. Install it:

CentOS, AlmaLinux and Red Hat:

sudo yum install mailx -y

Debian and Ubuntu:

sudo apt install mailutils

You also need an MTA such as Postfix to send mail.

Send a mail

mail -s 'Enter the subject' user@example.com

-s sets the subject. Type your message, then press Ctrl+D on an empty line to send. The screen shows EOT.

Send the message from a file

mail -s 'The Subject' user@example.com < /root/testemail.txt

Send with a pipe

echo 'THIS IS A TEST EMAIL' | mail -s 'Enter the subject' user@example.com

Several recipients

echo 'THIS IS A TEST EMAIL' | mail -s 'Enter the subject' user1@example.com,user2@example.com

CC and BCC

echo 'THIS IS A TEST EMAIL' | mail -s 'Enter the subject' -c cc1@example.com,cc2@example.com user@example.com

For a blind copy use -b.

Set the From name and address

With mailx:

echo 'THIS IS A TEST EMAIL' | mail -s 'Enter the subject' -r 'Tom <tom@example.com>' user@example.com

With GNU mailutils use -a "From: Tom <tom@example.com>".

Set a Reply-To address

echo 'THIS IS A TEST EMAIL' | mail -s 'Enter the subject' -S replyto=reply@example.com user@example.com

Attach a file

mailx:

echo 'See the attachment' | mail -s 'Report' -a /root/report.pdf user@example.com

GNU mailutils uses -A for attachments.

Use it in a script

#!/bin/bash
df -h | mail -s "Disk report for $(hostname)" admin@example.com

Add it to cron to send a report every day.

Quick recap

  • Install mailx or mailutils, and a working MTA like Postfix.
  • echo "text" | mail -s "Subject" user@example.com is the fastest way.