Linux mail command examples – send mails from command line

By | August 15, 2024

Send mails from command-line

Being able to send emails from command-line from a server is quite useful when you need to generate emails programatically from shell scripts or web applications for example.

This tutorial explains, how to use to the mail command on linux to send mails from the command-line using the mail command.

How the mail command works

For those who are curious about how exactly the mail command delivers the mails to the recipients, here is a little quick explanation.

The mail command invokes the standard sendmail binary (/usr/sbin/sendmail) which in turns connects to the local MTA to send the mail to its destination. The local MTA is a locally running smtp server that accepts mails on port 25.

mail command -> /usr/sbin/sendmail -> 
-> local MTA (smtp server port:25) -> recipient MTA (and Inbox)

This means that an smtp server like Postfix should be running on the machine where you intend to use the mail command. If none is running you get the error message "send-mail: Cannot open mail:25".

The mail command typically comes from a package named mailutils on ubuntu for instance. Without the mailutils package installed, you would get this:

$ mail -s "Hello World" [email protected]
Command 'mail' not found, but can be installed with:
sudo apt install mailutils
$

Moreover there would be no sendmail binary available on the system.

$ which sendmail
$

The sendmail command is available in a lot of packages which can be seen below:

$ sendmail
Command 'sendmail' not found, but can be installed with:
sudo apt install exim4-daemon-heavy  # version 4.97-4ubuntu4.1, or
sudo apt install exim4-daemon-light  # version 4.97-4ubuntu4.1
sudo apt install postfix             # version 3.8.4-1
sudo apt install courier-mta         # version 1.0.16-3.2
sudo apt install dma                 # version 0.13-1build1
sudo apt install esmtp-run           # version 1.2-18
sudo apt install msmtp-mta           # version 1.8.23-1ubuntu1
sudo apt install nullmailer          # version 1:2.2+10~g7ed88a0-2
sudo apt install opensmtpd           # version 7.4.0p1-1
sudo apt install sendmail-bin        # version 8.17.2-1
sudo apt install ssmtp               # version 2.64-11
$

Each package provides its own sendmail command version. So if you try to install 2 of them, there will likely be a conflict, and ubuntu would remove the previous one, before installing the next.

If you have a MTA like postfix installed, it will provide its own sendmail binary:

# dpkg -S $(which sendmail)
postfix: /usr/sbin/sendmail
#

The mailutils command itself does not have any sendmail binary, but installs another package like postfix to provide the binary.

$ apt-cache depends mailutils
mailutils
  Depends: mailutils-common
  Depends: libc6
  Depends: libcrypt1
  Depends: libfribidi0
  Depends: libgnutls30t64
  Depends: libgsasl18
  Depends: libldap2
  Depends: libmailutils9t64
  Depends: libncurses6
  Depends: libpam0g
  Depends: libreadline8t64
  Depends: libtinfo6
  Depends: libunistring5
  Breaks: <elm-me+>
  Breaks: <heirloom-mailx>
 |Recommends: <default-mta>
    postfix
  Recommends: <mail-transport-agent>
    esmtp-run
    exim4-daemon-light
    msmtp-mta
    nullmailer
    opensmtpd
    sendmail-bin
    ssmtp
    dma
    exim4-daemon-heavy
    postfix
  Suggests: mailutils-mh
  Suggests: mailutils-doc
$

If you have mail command installed but no sendmail executable binary available for invocation, then you could see an error message like the following:

$ echo "This is a test email" | mail -s "Test Email" [email protected]
mail: Cannot open mailer: No such file or directory
mail: cannot send message: No such file or directory
$

Install the mail command

The mail command is available from many different packages. These packages are available in the default repositores of most of the popular linux distributions like debian, ubuntu, centos and fedora.

Here is the list of some of the common packages that provide the mail command.

1. gnu mailutils
2. heirloom-mailx
3. bsd-mailx

Each flavor has a different set of options and supported features. For example the mail/mailx command from the heirloom-mailx package is capable of using an external smtp server to send messages, while the other two can use only a local smtp server.

In this tutorial we shall be using the mail command from the mailutils package, which is available on most Debian and Ubuntu based systems.

Use the apt-get command to install it

$ apt-get install mailutils

Now you should have the mail command ready to work.

mail command examples

Here are some examples of how to use the mail command to send mails from the command line. These examples shall give you a basic idea of the various options and features supported by the mail command.

Note: If you are trying to send a test mail to some mail provider like gmail or outlook, then you would need to run these commands on a server with proper configuration. If you try to send mail from you local machine or desktop, then most spam filters would probably block it.

1. Sending a simple mail

Run the command below, to send an email to [email protected]. The s option specifies the subject of the mail followed by the recipient email address.

$ mail -s "Hello World" [email protected]

The above command is not finished upon hitting Enter. Next you have to type in the message. When you're done, hit 'Ctrl-D' at the beginning of a line

$ mail -s "Hello World" [email protected]
Cc: 
Hi Peter
How are you
I am fine
Good Bye
<Ctrl+D>

The shell asks for the 'Cc' (Carbon copy) field. Enter the CC address and press enter or press enter without anything to skip.

From the next line type in your message. Pressing enter would create a new line in the message. Once you are done entering the message, press . Once you do that, the mail command would dispatch the message for delivery and done.

2. Subject and Message in a single line

To specify the message body in just one line of command use the following style

$ mail -s "This is the subject" [email protected] <<< 'This is the message'

Or like this

$ echo "This is the body" | mail -s "Subject" -aFrom:Harry\<[email protected]\> [email protected]

3. Take message from a file

If the email message is in a file then we can use it directly to send the mail. This is useful when calling the mail command from shell scripts or other programs written in perl or php for example.

$ mail -s "Hello World" [email protected] < /home/user/mailcontent.txt

Or a quick one liner

$ echo "This is the message body" | mail -s "This is the subject" [email protected]

4. Specify CC and BCC recipients

Other useful parameters in the mail command are:

-c email-address (CC - send a carbon copy to email-address)
-b email-address (BCC - send a blind carbon copy to email-address)

Here's and example of how you might use these options

$ mail -s "Hello World" [email protected] -c [email protected] -b [email protected]

5. Sending to multiple recipients

It is also possible to specify multiple recipients by joining them with a comma.

$ mail -s "Hello World" [email protected],[email protected]

6. Specify the FROM name and address

The "-a" option allows to specify additional header information to attach with the message. It can be used to provide the "FROM" name and address. Here is a quick example

# echo "This is the message body" | mail -s "This is the subject" [email protected] -aFrom:[email protected]

The a option basically adds additional headers. To specify the from name, use the following syntax.

$ echo "This is the body" | mail -s "Subject" -aFrom:Harry\<[email protected]\> [email protected]

Note that we have to escape the less/great arrows since they have special meaning for the shell prompt. When you are issuing the command from within some script, you would omit that.

7. Send mail to a local system user

To send mail to a local system user just use the username in place of the recipient address

$ mail -s "Hello World" username

You could also append "@hostname" to the username, where the hostname should be the hostname of the current system.

8. Verbose output

Sometimes when testing mail servers, you would want to check the SMTP commands being used by the mail command. Use the "-v" option for that

$ mail -v -s "This is the subject" [email protected] <<< 'This is the message'

If the mail fails to deliver due to an improperly configured mail server for example, the smtp command log will show what has gone wrong.

Send mail with attachments using Mutt

The mail command could do some basic things till now, but moving forward, it lacks important features like sending attachments.

So we have to use another command line tool called mutt. Mutt is like an enhanced version of the mail command with a very similar syntax.

Debian / Ubuntu users can install mutt with the apt command.

$ apt-get install mutt

Fedora / CentOS or Red Hat Enterprise Linux (RHEL) users:

$ yum install mutt

Now you are ready to send mail with attachments with command line interface.

Send a simple mail

$ echo "This is mutt from universe" | mutt -s "This is mutts subject" [email protected]

Send mail with attachment

Use the "a" option to specify the path of the file to attach

$ mutt -s "Subject" -a /path/to/file -- [email protected] < home/user/mailcontent.txt

According to the syntax of mutt options, it is necessary to separate the files and the recipients with a double dash "--". Also the "-a" option should be last one.

Send mail with bash/shell scripts

This example demonstrates how the output of a command can be used as the message in the email.
Here is an easy shell script that reports disc usage over mail.

#!/bin/bash
du -sh | mail -s "disk usage report" [email protected]

Open a new file and add the lines above to that file, save it and run on your box. You will receive an email that contains "du -sh" output.

Read mails

This is not something interesting and you would not be doing this in a real life scenario. It is just being shown for the sake of it.

The mail command can be used to read mails. Just run it without an options and it would list all the mails in your inbox

$ mail

Here's a sample output

$ mail
Heirloom mailx version 12.5 6/20/10.  Type ? for help.
"/var/mail/enlightened": 7 messages 3 unread
 O  1 Enlightened        Sat Dec  6 11:33   21/658   This is the subject
 O  2 Enlightened        Sat Dec  6 11:34  773/25549 This is the subject
 O  3 Enlightened        Sat Dec  6 16:43   20/633   This is the subject
 O  4 Enlightened        Sat Dec  6 16:44   20/633   This is the subject
 U  5 Mail Delivery Syst Sat Dec  6 16:50   74/2425  Undelivered Mail Returned to Sender
 U  6 Enlightened        Sat Dec  6 16:51   19/632   This is mutts subject
 U  7 Enlightened        Sat Dec  6 16:52   19/647   This is mutts subject
?

At the end is q question mark which is an interactive prompt waiting for your command. Simply enter the number of the email you want to read and hit enter. It would open up the mail then.

After you are done reading the email, enter 'q' and hit enter to come back. Enter z and hit enter to bring back the list of emails.

The mail command by default reads the emails from the directory "/var/mail/". So every user has a separate mail directory.

This way of storing and fetching mails is not very useful or practical in real life, where mail address consist of domain name along with username and a single server could be hosting emails for multiple domains.

Maildir-utils command

'mu' is a set of command-line tools for Linux/Unix that enable you to quickly find the e-mails you are looking for.

Debian/Ubuntu users can use the apt-get command to install it

# apt-get install maildir-utils

To search mails from william with subject report use the following command -

$ mu find from:william subject:report

To check the current mail configurations use the info option.

# mu-tool info
VERSION=2.99.97
SYSCONFDIR=/etc
MAILSPOOLDIR=/var/mail/
SCHEME=mbox
LOG_FACILITY=mail
.....

Notes and Resources

The mail command is a very basic command to send mails. It should be present and properly configured on any linux server, so that mails are generated and delivered properly.

The mail command is mostly used when you are writing bash scripts to send emails from a server in an automated fashion. Besides this, the mail command is not very useful as an email solution.

If you need to setup a complete email system on your server with the ability to send and receive emails on your own domain then go ahead and install applications like postfix, dovecot.

Check this article:
Install Postfix mail server and Dovecot on Ubuntu or Debian

If you are looking for a more powerful mailing program use commands like mailx, swaks etc. They have the necessary options to specify external smtp servers as well.

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

26 Comments

Linux mail command examples – send mails from command line
  1. Moonwatcher

    Aha! Maybe I understand? This not ’email’, but mail meaning a message sent to someone who works in the same workplace, for example? If this is the case it’s of no use to me at home — unless of couse I wish to send messages to myself!

    Am I right?

  2. Moonwatcher

    Hi Silver Moon

    Your article is beautifully explained, but the mail I sent never showed up. I checked: I did it the way you said.

    I have had success (sending) with alpine, though I can’t understand most of that program!

    Moonwatcher

  3. Angelo

    $ mail -s “This is the subject” [email protected] <<< "This is the message"

    In the example above, using double quotes for the message, I can include $ variables. Now, can I somehow get down to the second line (an enter) in the body of the message?

    Thank you.

  4. Anatoly Rozhkov

    cannot send message: Process exited with a non-zero status

    why does this keep happening, I’ve tried like over 10 different walk-throughs on how to configure emails, and all of them have ended with this message

    1. Anatoly Rozhkov

      I’ve figured out how to fix it, and found that ssmtp may be interfering postfix
      I’ve updated postfix and finally managed to send a message with end status 0, yet… it never arrived

  5. Arpit

    I am unable to send mail using sendmail to a particular email address(Distribution list). Please help me.
    Server details:- Linux 2.6.32-754.11.1.el6.x86_64 #1 SMP Tue Jan 22 17:25:23 EST 2019 x86_64 x86_64 x86_64 GNU/Linux

    Part of Code:-
    [email protected]
    echo From: $FROM > $MAIL_FILE
    echo Cc: $CC >> $MAIL_FILE
    echo To: $TO >> $MAIL_FILE
    echo Subject: “Notification: >> $MAIL_FILE


    /usr/lib/sendmail -t < $MAIL_FILE

  6. s gopi krishnan

    hi
    I need to mail the below information, How to capture and send mail. kindly help
    mail -s |”GG Daily Status Report” [email protected]

    GGSCI>info all
    Manager Prgname Status Lag CHKPT
    Extract EX_R01 Running 00:00:00 00 00:00:00

  7. pavlos

    $ sudo apt install mutt

    (installed)

    $ echo “This is mutt from universe” | mutt -s “This is mutts subject” [email protected]
    Error sending message, child exited 127 (Exec error.).

    Not working …

  8. selvakumar

    Hey..I’ve ran multiple comment into single line..using &&. then i got 2 line output.

    pwd && ls -altr | grep *INTD437*

    when try to send mail of 2 line output..pwd && ls -l | grep *INT* | mail -s “file output” [email protected]

    I’m only getting 1st line output in the mail. Can you suggest on this.

  9. Dustin

    Regarding BCC and CC addresses when sending from a single line. I was trying to use the syntax above to send to CC and BCC addresses, but all the addresses ended up being in the To: field of the email. After reading documentation for GNU Mailutils, I found that you need to specify options first and then the address list.

    $ mail [option…] [address…]

    So instead of:
    $ mail -s “Hello World” [email protected] -c [email protected] -b [email protected]

    I had to do:
    $ mail -s “Hello World” -c [email protected] -b [email protected] [email protected]

    Hopefully this helps someone out in the future.

  10. curious guy

    Hail Silver Moon, great article. Thanks!

    I would like to make an addendum regarding the last topic you have written about attaching a file using the “mutt” tool:
    For the reason of the “mailx” program being part of the POSIX Standard to server as a MUA, then I believe that the use of it would be more viable than the “mutt”. In addition, the [mailx] tool is not difficult to use. For more details: https://access.redhat.com/solutions/104833

  11. Joel

    I found your article to be concise and VERY helpful, thanks! I was having troubles sending automated mail with a bash script from a cron job where I wanted a complex, all text, message. I am going to browse the rest of your site now to see what other nuggets of useful info you have!

  12. steve

    I am using Linux Mint 13 (fully updated) installed all the packages listed in the article. Followed the tutorial and the commands work (sorta) but mail is never sent and their is no hcg directory in var/spool/mail , only a locked file called root and when I try to read the mail messages the command “mail” just brings up system log files and displays them as messages. Strange. Nothing at as indicated should happen in the tutorial.

Leave a Reply

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