Never Ending Security

It starts all here

How to send mails from the Linux command line


Linux mail command examples – send mails from command line


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) -> 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”.

Install the mail command

The mail command is available from many different packages. Here is the list –

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.

Use the mail command

Run the command below, to send an email to someone@example.com. The s option specifies the subject of the mail followed by the recipient email address.

$ mail -s "Hello World" someone@example.com

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" someone@example.com
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 <ctrl+d>. Once you do that, the mail command would dispatch the message for delivery and done.

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" user@yourmaildomain.com < /home/user/mailcontent.txt

Or a quick one liner

$ echo "This is the message body" | mail -s "This is the subject" mail@example.com

CC and BCC

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" user1@example.com -c usertocc@example.com -b usertobcc@example.com

Multiple recipients

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

$ mail -s "Hello World" user1@example.com,user2@example.com

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" mail@example.com -aFrom:sender@example.com

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\<harry@gmail.com\> someone@example.com

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.

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.

Send mail with attachments

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" someone@example.com

Send mail with attachment – Use the “a” option to specify the path of the file to attach

$ mutt -s "Subject" -a /path/to/file -- user@example.com < 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" user@yourmaildomain.com

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

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.

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.


9 mail/mailx command examples to send emails from command line on Linux


Send mails from command line

The mail command is an essential one that should be available on any linux server so that various services and other web applications can generate and transmit emails.

In the previous part we saw how the mail command can be used to send emails from the command line on your linux server.

In this tutorial we shall be using an enhanced version of the mail command. Its called mailx (or just mail when installed), and it can do many more things than what the older mail command from gnu mailutils package can do.

How does it work

The mail/mailx command needs a local smtp server (MTA) running in order to deliver the emails. THe route taken by the email is somewhat like this –

mail -> sendmail -> local MTA -> recipient MTA [Inbox]

The recipient MTA would be gmail’s smtp server if your recipient is someone at gmail.com for instance. For the local MTA, you need to install an smtp server like Postfix. A basic installation of Postfix with minimal configuration would work in most cases.

Install the mailx command

On Ubuntu/Debian based systems the mailx command is available from 2 different packages –

1. heirloom-mailx
2. bsd-mailx

We shall be using the heirloom-mailx package because it has more features and options.
On CentOS/Fedora based systems, there is only one package named “mailx” which is the heirloom package.

To find out what mailx package is installed on your system, check the “man mailx” output and scroll down to the end and you should see some useful information.

# ubuntu/debian
$ sudo apt-get install heirloom-mailx

# fedora/centos
$ sudo yum install mailx

Using the mailx command

Once installed, the mailx command can be directly referenced with the name mail, so you just type in that in the command line.

1. Simple mail

Run the following command, and then mailx would wait for you to enter the message of the email. You can hit enter for new lines. When done typing the message, press Ctrl+D and mailx would display EOT.

After than mailx automatically delivers the email to the destination.

$ mail -s "This is the subject" someone@example.com
Hi someone
How are you
I am fine
Bye
EOT

2. Take message from a file

The message body of the email can be taken from a file as well.

$ mail -s "This is Subject" someone@example.com < /path/to/file

The message can also be piped using the echo command –

$ echo "This is message body" | mail -s "This is Subject" someone@example.com

3. Multiple recipients

To send the mail to multiple recipients, specify all the emails separated by a comma

$ echo "This is message body" | mail -s "This is Subject" someone@example.com,someone2@example.com

4. CC and BCC

The “-c” and “-b” options can be used to add CC and BCC addresses respectively.

$ echo "This is message body" | mail -s "This is Subject" -c ccuser@example.com someone@example.com

5. Specify From name and address

To specify a “FROM” name and address, use the “-r” option. The name should be followed by the address wrapped in “<>”.

$ echo "This is message body" | mail -s "This is Subject" -r "Harry<harry@gmail.com>" someone@example.com

6. Specify “Reply-To” address

The reply to address is set with the internal option variable “replyto” using the “-S” option.

# replyto email
$ echo "This is message" | mail -s "Testing replyto" -S replyto="mark@gmail.com" someone@example.com

# replyto email with a name
$ echo "This is message" | mail -s "Testing replyto" -S replyto="Mark<mark@gmail.com>" someone@example.com

7. Attachments

Attachments can be added with the “-a” option.

$ echo "This is message body" | mail -s "This is Subject" -r "Harry<harry@gmail.com>" -a /path/to/file someone@example.com

8. Use external SMTP server

This is an exclusive feature, that you get only with heirloom mailx and not bsd mailx, or the mail command from gnu mailutils or the mutt command.

The mailx command can use an external smtp server to use to relay the message forward. The syntax is a bit lengthy but makes sense.

$ echo "This is the message body and contains the message" | mailx -v -r "someone@example.com" -s "This is the subject" -S smtp="mail.example.com:587" -S smtp-use-starttls -S smtp-auth=login -S smtp-auth-user="someone@example.com" -S smtp-auth-password="abc123" -S ssl-verify=ignore yourfriend@gmail.com

Here is a breakdown

$ echo "This is the message body and contains the message" | mailx -v \
> -r "someone@example.com" \
> -s "This is the subject" \
> -S smtp="mail.example.com:587" \
> -S smtp-use-starttls \
> -S smtp-auth=login \
> -S smtp-auth-user="someone@example.com" \
> -S smtp-auth-password="abc123" \
> -S ssl-verify=ignore \
> yourfriend@gmail.com

You can use the gmail smtp servers and send emails via your gmail account. That is so cool!
For gmail specifically you would need to enable less secure apps settings before you can send mail like that.

9. Verbose – watch smtp communication

When using external smtp servers, you can choose to watch the entire smtp communication that is done in the background. This is useful specially when testing or debugging smtp servers.

$ echo "This is the message body and contains the message from heirloom mailx" | mailx -v -s "This is the subject" -S smtp="smtp.gmail.com:587" -S smtp-use-starttls -S smtp-auth=login -S smtp-auth-user="mygmail@gmail.com" -S smtp-auth-password="mypassword" -S ssl-verify=ignore someone@example.com
Resolving host smtp.gmail.com . . . done.
Connecting to 74.125.68.109:587 . . . connected.
220 mx.google.com ESMTP je4sm32812877pbd.94 - gsmtp
>>> EHLO enlightened
250-mx.google.com at your service, [122.163.43.21]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
>>> STARTTLS
220 2.0.0 Ready to start TLS
>>> EHLO enlightened
250-mx.google.com at your service, [122.163.43.21]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
>>> AUTH LOGIN
334 VXNlcm5hbWU6
>>> Ymx1ZWJ1enppdEBnbWFpbC5jb20=
334 UGFzc3dvcmQ6
>>> KnJpc2hhYmgzKg==
235 2.7.0 Accepted
>>> MAIL FROM:<enlightened@enlightened>
250 2.1.0 OK je4sm32812877pbd.94 - gsmtp
>>> RCPT TO:<someone@example.com>
250 2.1.5 OK je4sm32812877pbd.94 - gsmtp
>>> DATA
354  Go ahead je4sm32812877pbd.94 - gsmtp
>>> .
250 2.0.0 OK 1417930703 je4sm32812877pbd.94 - gsmtp
>>> QUIT
221 2.0.0 closing connection je4sm32812877pbd.94 - gsmtp

Troubleshooting

In case the mails are not being delivered properly you need to check a few things. The first thing to check is that an smtp server (mta) is running locally. The netstat command can tell that

$ sudo netstat -ltnp | grep 25
[sudo] password for enlightened: 
tcp        0      0 0.0.0.0:25              0.0.0.0:*               LISTEN      2541/master     
tcp6       0      0 :::25                   :::*                    LISTEN      2541/master

If an stmp server like Postfix is running and still mails are not going, then try re-configuring Postfix for example. On Ubuntu/Debian systems, this can be done with the dpkg-reconfigure command

$ sudo dpkg-reconfigure postfix

Then retry, the mail command and it should work. If it still doesn’t, try contacting your server provider.

No mails from local systems

If you try to send mails from your local computer to a gmail address, your mail would most likely be rejected, so don’t try doing that.

This is because ordinary computers connected to internet address have an ip address that is not associated with any valid domain as such, and gmail strictly verifies such credentials before approving any mail to go through.

Notes and Resources

Apart from mailx, there are other tools like Swaks and smtp-cli that can be used to send mails from command line and support various features like specifying smtp servers and adding attachments and so on.

However the mailx command is available in the default repositories of most common distros, so can be installed easily. Further it maintains a syntax very similar to that of the mail command which makes it a drop in replacement for the older mail command.

The mailx command is even capable of reading mails from remote IMAP servers, but that is something we kept out of this post and would talk later. To learn more check the man page for the mailx command with “man mailx”.


Send mail from command line with external smtp server on Linux


Send mail via SMTP servers

The default mail command on the Linux terminal, uses the local smtp server (mta) on port 25 to transmit emails. However at times you need to specify an external smtp server to use for sending mails.

For example you have just setup an smtp server, like Postfix or Exim, then you would want to test it out to check if it is receiving and relaying emails properly or not.

Being able to send mails from command line using this external smtp server is quick rather than having to setup a mail client like Thunderbird on your local machine.

1. mailx command

The mailx command is available from many different packages like mailutils, heirloom-mailx etc. We shall be using heirloom-mailx since it allows to specify smtp connection details in a single command and issue and email quickly.

$ sudo apt-get install heirloom-mailx

Now send an email with an external smtp server like this –

echo "This is the message body and contains the message" | mailx -v -r "someone@example.com" -s "This is the subject" -S smtp="mail.example.com:587" -S smtp-use-starttls -S smtp-auth=login -S smtp-auth-user="someone@example.com" -S smtp-auth-password="abc123" -S ssl-verify=ignore yourfriend@gmail.com

Here is a step by step version of the same command –

$ echo "This is the message body and contains the message" | mailx -v \
> -r "someone@example.com" \
> -s "This is the subject" \
> -S smtp="mail.example.com:587" \
> -S smtp-use-starttls \
> -S smtp-auth=login \
> -S smtp-auth-user="someone@example.com" \
> -S smtp-auth-password="abc123" \
> -S ssl-verify=ignore \
> yourfriend@gmail.com

Make sure to use the correct settings, like port number, authentication mechanism etc. The command would produce verbose output giving full details of the smtp communication that goes on behind, making it very easy to test and debug.

2. Swaks command

Swaks (Swiss army knife for SMTP) is a simple command line tool that can be used to test smtp servers to check if they are doing they job properly. It supports TLS as well.

Install swaks on Ubuntu/Debian with the following command

$ sudo apt-get install swaks

Now send the email

$ echo "This is the message body" | swaks --to someone@gmail.com --from "you@example.com" --server mail.example.com --auth LOGIN --auth-user "you@example.com" --auth-password "abc123" -tls

All the options are pretty self explanatory. The “–server” option specifies the external SMTP server to use, “–auth” specifies the type of authentication. The “-tls” option tells swaks to use STARTTLS.

Check the man page for more options.

Advertisements

One response to “How to send mails from the Linux command line

  1. http://bigdownloadgames.com/ 17 May 2015 at 10:18

    When someone writes an paragraph he/she retains the idea of a user inn his/her miond that how a user can understand it.
    Therefore that’s why this piece off writing is outstdanding.

    Thanks!

Leave a Reply

Please log in using one of these methods to post your comment:

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