Sendmail in a shell script

Someone asked me to write a script that will send mails to a particular email id. I had not used any such script before. So I had to search quite a lot. Here is the simple shell script that will send mail to the specified email ids. Currently it does not support attachments.

# Name: SendMail
# Purpose: To send mails using the sendmail command
# Usage: SendMail
# Owner: Ketan Joshi
# Setting: Just change the variables at the start of the script to
#          appropriate values. Create a message by modifying the string BODY
#          You can even have html tags in the body.
# Limitation: Currently, this does not support attachments.
#Temporary file for containing the mail message
tmp=/tmp/mail-body-`date +%F`;
touch $tmp && chmod 600 $tmp;
#Set up the various headers for sendmail to use
SUBJECT=’Test Mail’;
CONTENTType=”text/html; charset=us-ascii”;
#Here write the content of your mail.
<b>Hello from ketan.</b>
This is test mail.

echo Sending the mail.
echo -e “To: $TO” > $tmp;
echo -e “Cc: $CC” >> $tmp;
echo -e “From: $FROM” >> $tmp;
echo -e “Content-Type: $CONTENTType”>>$tmp;
echo -e “MIME-Version: $MIMEVersion”>>$tmp;
echo -e “Subject: $SUBJECT”>>$tmp;
echo -e “Body: $BODY”>>$tmp;

/usr/sbin/sendmail -t < $tmp;

rm -rf $tmp;


5 Responses to Sendmail in a shell script

  1. Ted Burrett says:

    I noticed that this is not the first time you write about the topic. Why have you chosen it again?

  2. Prathamesh says:


    This script is works, but at the reciver the mail is recived as a spam, bulk mail.what is the solution for this? Reply..

    • KeJo says:

      add the mail id from which the script sends mail to your address book. This will make sure that the mail is not marked as spam.

  3. prathamesh says:

    yes thanks for previous Rply. it works now.. but i need to set this script to be run as a cronjob i have set the job as:

    */10 * * * * /root/

    where as , contains the above sendmail script
    it is not working on server ? where as manually running shell, it works, what to do for that?

  4. Using python for sending mail gives you additional options and extensibility. Usage of TLS/SSL for smtp servers are supported in python’s library. easy to get arguments via shell also.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: