Friday, February 17, 2006

Sending Mail from command line "mail"

Check this post which has a good explanation on using mail command.

Sending Mails through Command line "mail"

If you have been using Linux for sometime now then you must have used the mail command to send mails.

There is a Mail Client "Mutt" that enables you to send mails from shell but I would still prefer a one liner .... command which is much quicker to send mails,
say for eg. say you want to schedule mails for cron jobs.

Thats why I prefer the good old "mail" command

I have a Postfix running as a mail server on my system which accepts mail from
sriram.com domain.

Now my requirement is to be able to use "mail" command with postfix.

Step 1

I downloaded a command line smtp client msmtp


root@mybox sriram]# urpmi msmtp
ftp://gd.tuwien.ac.at/pub/linux/Mandriva/official/2006.0/i586/media/
contrib/msmtp-1.4.4-1mdk.i586.rpm
installing msmtp-1.4.4-1mdk.i586.rpm from /var/cache/urpmi/rpms
Preparing... #############################################
1/1: msmtp #############################################

[root@mybox sriram]#


By default "mail" command can be found in most of the linux system.


Step 2

I created a .msmtprc file inside the home directory /home/sriram

This is created to tell msmtp which SMTP server you want to use, and the information needed to access that account.

[root@mybox sriram]# cat .msmtprc
account default
auto_from off
host 10.10.93.220
from sriram@sriram.com
user sriram@gmail.com

#account default
#auto_from off
#host smtp.gmail.com
#from sriram@gmail.com
#auth on
#password mypassword
#user sriram@gmail.com
#tls on
[root@mybox sriram]#


The above hashed lines are comment, you can follow the syntax given in the hash lines if you are using a mail server which has smtp authentication
configured or if you wish to use a external mail server.

Step 3

Now to tell "mail" command to use "msmtp"

I created a file .mailrc in /home/directory and added a line

set sendmail=/usr/bin/msmtp

Note: Make sure your msmtp is in /usr/bin.

[root@mybox sriram]# which msmtp
/usr/bin/msmtp
[root@mybox sriram]#

Thats it now the "mail" command should work !!!

Now using mail commands,

$ mail sriram@linux.com

Subject: Test email

I'm sending you this email.

^D

(The ^D is Control-D, used to denote an end of file.)

Now the nice thing about the old "mail" command is that it would
accept anything from standard input. So if I wanted to send sriram a
really long email I could put it in a big file, and pipe it into the

mail command:
$ cat bigfile.txt | mail -s "Dear Sriram" sriram@gmail.com

or

$ mail -s "Dear Sriram" sriram@gmail.com <. bigfile.txt


No comments: