Thursday, October 28, 2010

Sending mails from command line


Sending mails using mail:
mail (mailx is the newer version) is a fantastic program that can be used for sending email from command line or from within scripts.
The following example will send an email to admin@yeswedeal.com, with subject “Apache is down” and text “Please check Apache at host name of the server”
echo “Please check Apache at `hostname`” | mail -s “Apache is down” admin@yeswedeal.com
We can cat the contents of any text file, for example, log file and it will be sent to the recipient specified
cat “/var/log/apache2/error.log” | mail -s “Apache is down” admin@yeswedeal.com
To attach a file, other than a text one, we need to uuencode (unix to unix encode) it before sending
uuencode banner.jpg banner_out.jpg | mail webmaster@yeswedeal.com
The banner.jpg is the name of input file and banner_out.jpg is the output uuencoded file that we will be sent by mail.
To have text sent alogwith the attachment, we can cat or echo that text too
(cat /var/log/apache2/error.log;uuencode banner.jpg banner.jpg) | mail -s pic webmaster@yeswedeal.com

Sending mails from using mutt:
With mutt, its same as using mail.
echo “Please check Apache at `hostname`” | mutt -s “Apache is down” admin@yeswedeal.com
or we can cat the contents of a text file to show as body text
cat /var/log/apache2/error.log | mutt -s “Apache is down” admin@yeswedeal.com
OR
mutt -s “Apache is down” admin@yeswedeal.com
To send an empty body mail, use an empty line as the mail body:
echo | mutt -s “Software upgrades for `hostname`” admin@yeswedeal.com
To attach a binary file, its even easier with mutt, just use the -a option
echo | mutt -s “New logo for the company” -a logo.gif webmaster@yeswedeal.com

Post a Comment