home   articles   tags   browse code   

BASH - Linux sendmail script


 

Most linux distributions come with the sendmail application. Some interpreted languages like php use it for its mail() function. I have even seen command line php used from bash for its mail functions as opposed to the command line sendmail. When you are bash scripting, it is often better to use sendmail directly as opposed to adding the overhead, complexity and extra dependency (for portability) of php.

Here is how to send a simple email using linux sendmail, for use in a cronjob script. These are generally used for administrative purposes, so a text-only email is usually just fine. We also have an article about using bash and sendmail with an attachment.


#!/bin/bash
#requires: date,sendmail
function fappend {
    echo "$2">>$1;
}
YYYYMMDD=`date +%Y%m%d`

# CHANGE THESE
TOEMAIL="recipient@email.com";
FREMAIL="crondaemon@65.101.11.232";
SUBJECT="Daily Backup - $YYYYMMDD";
MSGBODY="This is your daily backup notice";

# DON'T CHANGE ANYTHING BELOW
TMP="/tmp/tmpfil_123"$RANDOM;

rm -rf $TMP;
fappend $TMP "From: $FREMAIL";
fappend $TMP "To: $TOEMAIL";
fappend $TMP "Reply-To: $FREMAIL";
fappend $TMP "Subject: $SUBJECT";
fappend $TMP "";
fappend $TMP "$MSGBODY";
fappend $TMP "";
fappend $TMP "";
cat $TMP|sendmail -t;
rm $TMP;


Note: when i put this in a cronjob I usually have to replace 'sendmail' above with '/usr/sbin/sendmail'. To find out where sendmail is on your system type:
[root@server /home] which sendmail


 

 
James Randal on Feb 3rd, 2010 12:20 am said:
what is the rm -rf for ?? ;)
 

alex on Mar 23rd, 2010 10:10 am said:
instead of TMP="/tmp/tmpfil_123"$RANDOM; you could have written TMP=`mktemp`
 

Dama on Jul 28th, 2010 3:52 pm said:
How can I send a HTML email using the above script?
 



 

 



Related Articles
 




home  |  privacy policy  |  terms of use  |  contact  


©2010, Zedwood Digital