Showing posts with label Linux mail. Show all posts
Showing posts with label Linux mail. Show all posts

Tuesday, 6 August 2019

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.

1. 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 . 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" somebody@example.com <<< 'This is the message'
Or like this
$ echo "This is the body" | mail -s "Subject" -aFrom:Harry\<harry@gmail.com\> someone@example.com

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" 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

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

5. Sending to 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

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

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

Send mail from command line with external smtp server on Linux

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.
Check out the previous post on mailx command here -
9 mail/mailx command examples to send emails from command line on Linux

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.

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 a previous post on mail command 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 VXNlcmU6
>>> YmnbWFpbC5jb20=
334 UGFzcmQ6
>>> KnJgzKg==
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".

Thursday, 1 August 2019

Mail Command Examples in Unix / Linux Tutorial

The Mail command in unix or linux system is used to send emails to the users, to read the received emails, to delete the emails etc. Mail command will come in handy especially when writing automated scripts. For example, you have written an automated script for taking weekly backup of oracle database. How to know the status of backup, whether it is succeeded or not? In this case, sending an email from the automated script at the end of the backup will be helpful in knowing the status.



The syntax of mail command is:

mail [options] to-address [-- sendmail-options]

The options of mail command are listed below:

-v : Verbose mode. Delivery details are displayed on the terminal.
-s : Specify the subject of the mail
-c : Send carbon copies of the mail to the list of users. This is like cc option in Microsoft outlook.
-b : Send blind copies of the mail to the list of users. This is like bcc option in outlook.
-f : Read the contents of the mailbox
-r : Specify the from address in send mail options.

Mail Command Examples - Sending Emails:

1. Sending sample email to user

The basic functionality of the mail command in unix or linux system is to send an email to the user.

echo "Mail body" | mail -s "Mail subject" to@example.com

Here the echo statement is used for specifying the body of the email. The -s option is used for specifying the mail subject. The mail command sends the email to the user to@example.com

2. Specifying the body in a file

You want to compose a mail which contains 100 lines in the body. Specifying the body with the echo statement is a tedious process. So write the contents of the body in a file and send the mail using one of the following options:

Using cat statement:

cat body.txt | mail -s "Mail subject" to@example.com

Using input redirection operator

mail -s "Mail subject" to@example.com < body.txt

Here the body.txt file contains the body of the email. 3. Send mail to more than one user You can send email to more than one user by specifying the users in comma separated list.

mail -s "Mail subject" "user1@example.com,user2@example.com" < body.txt

4. Using the cc and bcc option You can copy the emails to more number of users by using the -c and -b options. An example is shown below:

mail -s "Mail subject" -c "ccuser@gmail.com" -b "bccuser@yahoo.com" "user@example.com" < body.txt

5. Specifying the from address So far the above examples send the emails with from address as the logged in user. You can explicitly specify the from-address using the -r option.

cat body.txt | mail -s "Mail subject" "to-user@example.com" -- -r "from-user@example.com"

6. Attaching files. The mail command does not provide an option for attaching files. There is a workaround for attaching files using the uuencode command. Pipe the output of uuencode command for attaching files.

uuencode attachment-file | mail -s "Mail subject" "to-user@example.com" < body.txt

Mail Command Examples - Reading Emails:

1. Viewing all the received emails Simply type the mail and then press enter to view the received emails.

mail

Another way of viewing the emails is using the -f option. This is shown below:

> mail -f /var/spool/mail/user

Mail version 8.1 6/6/93.  Type ? for help.
"/var/spool/mail/user": 2 messages 2 new
>N  1 root@hostname  Tue May 17 00:00  21/1013  "Mail subject 1"
 N  2 root@hostname  Wed May 18 00:00  21/1053  "Mail subject 2"
&

From the above output, you can see that, it displays the from-address, date and subject of the emails in the inbox. It also displays the ampersand (&) prompt at the end. To go back to the main prompt, type CTRL+z or CTRL+d depending on your operating system and press enter. The ampersand prompt allows you to read, reply, navigate and delete the emails.

2. Reading an email.

To read the Nth email, just enter the mail number at the ampersand prompt and press enter. This is shown below:

> mail -f /var/spool/mail/user

Mail version 8.1 6/6/93.  Type ? for help.
"/var/spool/mail/user": 2 messages 2 new
>N  1 root@hostname  Tue May 17 00:00  21/1013  "Mail subject 1"
 N  2 root@hostname  Wed May 18 00:00  21/1053  "Mail subject 2"
&2
Message 2:
From root@hostname  Wed May 18 00:00  21/1053
---------------
Subject: Mail subject 2
------------

This displays the second email details.

3. Navigating through inbox emails. To go to the next email, enter the + symbol. To go back to the previous email, enter the - symbol at the ampersand prompt.

&-
Message 1:
From root@hostname  Tue May 17 00:00  21/1013
---------------
Subject: Mail subject 1
------------

4. Replying email. Once you have read an email, you can give reply to the mail by typing "reply" and pressing enter.

&reply
To: root@hostname
    root@hostname
Subject: Re: Mail subject1


5. Deleting emails. You can delete a read email by typing the d and pressing enter. You can also specify the email numbers to d option for deleting them.

To delete read email
&d
To delete emails 1 and 2
&d 1 2
To delete range emails from 10 to 30
&d 10-30
To delete all emails in the mbox (mail box)
&d *