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=`mktemp` 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
code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)
James Randal
on
2010-02-03 07:20:39
what is the rm -rf for ?? ;)
|
alex
on
2010-03-23 16:10:01
instead of
TMP="/tmp/tmpfil_123"$RANDOM; you could have written TMP=`mktemp` |
Dama
on
2010-07-28 21:52:13
How can I send a HTML email using the above script?
|
Taj
on
2011-02-03 18:53:46
Thank you so much !!!!!!!!!!!. This really helped me. You rock !!!!!
|
Chris
on
2011-03-18 08:50:56
Maybe this is useful for anyone (sorry for the linebreak issues in this comment...):
If you want to use linebreaks in $MSGBODY, a simple n won't do (at least it didn't for me). If you hardcode the variable in your script, just press Enter instead of inserting a n -> MSGBODY="Hi there, I just wanted to tell you... bye" If this doesn't satisfy your eyes because of the formatting of your script, there's another way: MSGBODYTXT="Hi there,nnI just wanted to tell you...nnbye"; MSGBODY=`echo -e "$MSGBODYTXT"` Of course this also works out well if you use a script's parameter instead of $MSGBODYTXT - e.g. in combination with a sort of signature: (ran the script with 1st parameter "Hi therennblabla") SIGTXT="nnConcernedly YoursnnSimona Silly" MSGBODY=`echo -e "$1" "$SIGTXT"` |
Chris
on
2011-03-18 08:52:08
imagine any "n" or "nn" that doesn't make sense with an ESCAPE before it...
|