Send mail bash script

The mail command can be used under Linux or UNIX bash / ksh / csh shell to send an email. To send a message to one or more people, mail can be invoked with arguments which are the names of people to whom the mail will be sent. You are then expected to type in your message, followed by an ‘control-D’ at the beginning of a line. However, using the following syntax one can send email easily:
mail -s ‘Subject’ you@example.com Sample Shell Script

Here is what you need to put in a shell script:

#!/bin/bash
# script to send simple email 
# email subject
SUBJECT="SET-EMAIL-SUBJECT"
# Email To ?
EMAIL="admin@somewhere.com"
# Email text/message
EMAILMESSAGE="/tmp/emailmessage.txt"
echo "This is an email message test"> $EMAILMESSAGE
echo "This is email text" >>$EMAILMESSAGE
# send an email using /bin/mail
/bin/mail -s "$SUBJECT" "$EMAIL" < $EMAILMESSAGE

See also: Sending mail with attachment from command line/shell

Meet the Author

Admin

I like chocolate, gadgets, open source software, photography, traveling and all shades of green colors. I love spending time with fun loving friends and family members. This is my own online journal.

66 comments… add one
  • Deepa Jan 2, 2006, 10:50 pm

    Thanks …Really useful code..I searched a lot many places on Net …U r gr8! such simple details very much needed for a newbie like me.

  • Andrew Mar 22, 2006, 5:09 pm

    Another way to do it would be:

    echo $EMAILMESSAGE | /bin/mail -s “$SUBJECT” “$EMAIL”

    That way you don’t have to create a separate file for it.

  • Asela Jun 1, 2006, 5:53 am

    Thanx.

  • Mason Feb 13, 2007, 10:40 pm

    Another way is to use a “here” doc:

    /bin/mail -s “$SUBJECT” “$EMAIL”

  • Mason Feb 13, 2007, 10:41 pm

    Another way is to use a “here” doc:

    /bin/mail -s “$SUBJECT” “$EMAIL” <<EOM
    Your
    message
    goes
    here
    EOM

  • Walter Mar 8, 2007, 9:44 am

    Do i have to set up a mail server before executing the above mail script.
    I dont have a mail server. So Can i use the yahoo mail server with the script?

  • nixCraft Mar 8, 2007, 10:54 am

    You need to have forwarding smtp or working mail server.

  • sanya Mar 26, 2007, 5:44 am

    how can i know that there is a forwarding smtp or working mail server

  • ted loud Jul 8, 2007, 10:08 pm

    Do anybody know what i am doing wrong?

    script:

    #! /bin/sh
    SUBJECT=”SET-EMAIL-SUBJECT”
    EMAIL=”mymail@ad.dy”
    EMAILMESSAGE=”pathtofile”

    echo “This is an email message test” > $EMAILMESSAGE
    echo “This is email text” >> $EMAILMESSAGE

    /bin/mail -s “$SUBJECT” “$EMAIL”

  • ted loud Jul 8, 2007, 10:09 pm

    I copied this together, but it not works. Is a mail/smtp server necessary?

    I want to send out generated mails (in text and html) with attached binaries. the mails are ready, but my thunderbird supports no sending of fully generated source, if i compose the drafts file or import eml. On sending it wants to reattach the binaries and that goes wrong. Therefore i want to send the prepared mail source to my smtp server. Any idea how I could handle this?

    grz skr

  • vivek Jul 9, 2007, 7:27 pm

    What error do you get ?

  • Ron Jul 17, 2007, 2:05 am

    The last line of the script looks to be the problem. You are running mail with an address and subject but ~without~ the file you’ve created. You might want to use the line that Andrew gave earlier:

    echo $EMAILMESSAGE | /bin/mail -s “$SUBJECT” “$EMAIL”

    BTW, I just published a shell scripting book that might be helpful. One of the chapters discusses this very subject including emailing attachments from the command line. You can find it at Amazon or many other online stores.

    http://www.amazon.com/Shell-Script-Pearls-Ron-Peters/dp/0615141056

    Ron Peters

  • satish Sep 20, 2007, 4:41 am

    i need to send mail from bash shell script using my existing SMTP mail server. How to go about it….

  • ZZarko Mar 4, 2008, 5:16 pm

    You could try something like
    mail -s "mail subject" john@doe.com -a "Reply-To: " <<< "message text"
    if you need your SMTP for only Reply-To functionality.

  • ZZarko Mar 4, 2008, 5:21 pm

    You could try something like

    mail -s “mail subject” john@doe.com -a “Reply-To: &ltmy@address.com&gt” &lt&lt&lt “message text”

    if you need your SMTP for only Reply-To functionality.
    (my previous post somehow got altered; wrong quote characters and missing part of text, I guess because of using less than and greather than symbols).

  • Mayur Mar 17, 2008, 12:46 pm

    Hi,

    this had me perlexed for days. mail doesn’t work, or give an error (unless I do it through my hosting company). Why? Because mail does not allow you to specify an smtp sever to relay your mail through, and unless you can go through the the grief of setting up you machine as a bonafide mail server, you’re attempts will get rejected by the recepient as spam (without informing you).

    Solution:
    use nail, which does allow you to specify an smtp server to relay your mail through. You don’t need to go through any sendmail config files.

    http://forums.fedoraforum.org/showthread.php?t=143690
    “Rupert Pupkin”
    The problem with the standard ‘mail’ command is that it assumes that the machine it is running on is a full-fledged SMTP server. So unless you’ve configured your machine to be a bonafide mail server (or to act as an SMTP relay), then your mail will not go anywhere outside your machine (i.e. it will only work for addresses local to your machine, e.g. some_user@localhost). There is no way to specify an external SMTP server (like your ISP’s) to use with the ‘mail’ command. That’s why you’re getting a dead letter.

    If you want a command-line mailer that does support using an external SMTP server, then get nail from Fedora Extras. Nail supports specifying an external SMTP server. You can do this on a per-mail basis, like this:

    nail -r “myaddress@something.com” -s “Some subject” -S smtp=some.smtp.server info@company.com < msg.txt

    or you can permanently set the SMTP server in your ~/.mailrc file (or /etc/nail.rc if you want to set it system-wide), which removes the need for using the “-S smtp=…” option on the command-line:

    set smtp=some.smtp.server

    See the nail man page for more details. In my opinion, no one should be using ‘mail’ anymore, nail is vastly superior.”

  • kjkl Apr 29, 2008, 1:34 am

    I copied your script but mine says… “/bin/mail No such file or directory…” ———-> Whats that man?!?!

  • Gaurav May 6, 2008, 6:04 am

    Great stuff here.
    But how do you send inline attachment in a mail. eg.
    START of MAIL
    Text1
    Figure1
    Text2
    Figure2
    ….
    ENDofMAIL

    We can assume we have the text and the figures stored in convenient files.

  • warez Nov 14, 2008, 8:56 am

    No such file or directory? you’re probably using ubuntu/ debian ..
    try replacing ‘/bin/mail’ with ‘/usr/bin/mail’
    cheers

  • manik Dec 11, 2008, 5:41 am

    please some one help me out to write a shell script code for sending email after checking status of other pc’s in LAN by using ping command.

    please help me fast. Its urgent.

  • Satheesh Mar 12, 2009, 11:44 am

    Hi

    I need to email a file when it gets created, the script has to check for the file that was created for today date and then send it to the recipient, is it possible to do this in this script.

  • Christopher Barry Apr 9, 2009, 8:28 pm

    sends an email with/without attachment and optional importance level

    function sendEmail ()
    {
        [[ "$#" -lt "3" ]] && echo "$FUNCNAME [-a attachment] To 'subject' 'msg txt or file' [importance]" && return 1
        case ${1} in
    	-a)
    	    local attachment=${2}
    	    local alertTo=${3}
    	    local subject="${4}"
    	    local msgbody="${5}"
    	    local importance=${6:-normal}
    	    if [ ! -f ${attachment} ]; then
    		echo "Attachment not found. Exiting."
    		return 1
    	    fi
    	    if [ -f "${msgbody}" ]; then
    		doMsg="cat ${msgbody}"
    	    else
    		doMsg="echo ${msgbody}"
    	    fi
    	    ${doMsg} | /usr/bin/mutt -a ${attachment} -s "${subject}" -e "my_hdr importance:${importance}" "${alertTo}"
    	    rtn=$?
    	    ;;
    	*)
    	    local alertTo=${1}
    	    local subject="${2}"
    	    local msgbody="${3}"
    	    local importance=${4:-normal}
    	    if [ -f "${msgbody}" ]; then
    		doMsg="cat ${msgbody}"
    	    else
    		doMsg="echo ${msgbody}"
    	    fi
    	    ${doMsg} | /usr/bin/mutt -s "${subject}" -e "my_hdr importance:${importance}" "${alertTo}"
    	    rtn=$?
    	    ;;
        esac
        return $rtn
    }
  • Granty May 1, 2009, 9:27 pm

    Hello everyone!

    Can somebody help me to write a bash that sends email to recipients. The adress will come frome a file e.g email.txt. this file containes an adress(email) and a name. If there are more recipients they will separated with an ; . So the script must get the email andress and the text from another file like text.txt. But The text of the email begins with a Dear xy that comes from the email.txt name section.

    How can i do this?
    Please its urgent.

  • Kevin May 20, 2009, 7:04 am

    Thanks vivek for your help on the wonderful script for sending email . It was easy to follow and implement. worked liked a magic..

    Have a nice time :)

  • asad Jul 3, 2009, 11:56 am

    I am using Ubuntu
    tried the script, even with /usr/bin/mail but got this error:

    /usr/bin/maill : No such file or directory

    any idea, what am I missing?

  • vivek Jul 5, 2009, 4:34 am

    Install mail command by tying:

    sudo apt-get install mailutils
  • Alex Jul 19, 2009, 1:51 am

    Any time u don’t know the exact location of an aplication in you machine, just tipe
    $ wich mail /usr/bin/mail

    There u also realize if u have it or not XD

  • Rajesh Arora Jul 27, 2009, 5:56 am

    Thanks Vivek and Andrew for this wondeful insight on the email functionality.
    Raj

  • prathamesh Jul 28, 2009, 6:16 am

    What if i would like to include my own file as a mail body and To, Cc, Bcc, ?

  • Pradip Nov 17, 2009, 8:42 pm

    Thanks !!!!

  • Doug Nakatomi Nov 18, 2009, 12:29 am

    Thanks for the code!
    I used it to make a quick page.sh script, which anyone is welcome to use.
    I added a date +%s (unix seconds timestamp) to the tmp file name, and rm’d it at the end.

    #!/bin/bash
    #Author : dougnaka@gmail.com
    #Description : Quick alert/page script, edit EMAIL="" to include a comma separated list of emails to send to
    #Usage : page.sh "Short or long message"
    if [ "${1}" ]
     then
      SUBJECT="[ALERT] ${1}"
      EMAIL="someone@example.com,someone2@example.com"
      EMAILMESSAGE="/tmp/`date +%s`-message"
      echo "ALERT: at `date`" > ${EMAILMESSAGE}
      echo "${1}" >> ${EMAILMESSAGE}
      echo "From `hostname`" >> ${EMAILMESSAGE}
      mail -s "${SUBJECT}" "${EMAIL}" < ${EMAILMESSAGE}
      /bin/rm ${EMAILMESSAGE}
    else
     echo "Usage: ${0} MESSAGE"
     exit 1
    fi
  • Ken Dec 2, 2009, 7:51 pm

    Doug,
    Most linuxes should come with mktemp, which you could use to make a unique filename in the /tmp directory. $EMAILMESSAGE becomes:

    EMAILMESSAGE=`mktemp`

  • enrique Jan 4, 2010, 4:51 pm

    that’s fine
    my server requires authentication, how to do so?

  • Abdel Jan 14, 2010, 9:55 am

    Hi guys,

    Can someone help me on this,

    I need a Bash Scrinting how can I send a mail with a Ascii art en figlet programed to my email address.

    Rgrds,
    Abdel

  • Gerry Mar 18, 2010, 12:12 am

    Thanks. It worked, and well. Accomplished what I needed with a minimum of effort.

  • kiran Mar 23, 2010, 11:13 am

    But same script not working in my pc , wt to do??

    Regards
    kiran

  • Rishabh May 26, 2010, 6:09 pm

    Thanks,for such wonderfull discussion.I have different issue i have to send an autogenerated mail without using sendmail(sendmail is not configured).So any idea or script appreciated.

  • NUSTIAN Jun 2, 2010, 6:49 pm

    How can I send with the help of this script an email in which I can specify sender’s address.
    suppose I want to send an email to address (e.g. to_mail@address.com) and I want to mention also sender’s address (e.g. from_some1@address.com)

    plz help me….

  • cem Aug 18, 2010, 7:55 am

    Great job man.

    The script worked with mailx option for me.
    Thanks man!

  • proghack Oct 13, 2010, 4:01 am

    Hi ,
    I need to sent email to multiple user . However i use tis code its only sent to 1st email address.
    EMAIL = ” allan@gmail.com bruce@gmail.com jack@gmail.com
    echo $EMAILMESSAGE | /bin/mail -s “$SUBJECT” “$EMAIL”

    Can i know where my mistake?

  • saravanan Oct 22, 2010, 1:12 pm

    I have the bash script which is running fine (means – I’m able to get the mail once the script ran) in desktop (Mail box – “Use Cached Exchange Mode” was unchecked). and the same same which is not working in my laptop (Mail box – “Use Cached Exchange Mode” checked here).

    Please can someone help me to fix this issue. Your help much appreciated. Thanks in advance.

  • Anonymous Dec 7, 2010, 8:49 pm

    Thanks for starting this discussion.

    After looking at mail, nail, mutt and sSMTP, it seems that nail is the only utility that allows passing a non-standard SMTP port.

  • Bard Dec 7, 2010, 8:50 pm

    Thanks for starting this discussion.

    After looking at mail, nail, mutt and sSMTP, it seems that nail is the only utility that allows passing a non-standard SMTP port.

  • Bard Dec 7, 2010, 11:51 pm

    nail worked for CentOS.

    For Ubuntu, I have used the package “heirloom-mailx” from this site:

    http://http.us.debian.org/debian/pool/main/h/heirloom-mailx/

    You might need to try different versions. The regular mailx does not allow nail syntax.

  • naresh Jan 17, 2011, 2:54 pm

    hi,
    i used the same code but unable to get the xls attachement.
    This is my code—————
    SUBJECT=”SET-EMAIL-SUBJECT”
    # Email To ?
    EMAIL=”anand.naresh.kumar@accenture.com”
    # Email text/message
    EMAILMESSAGE=”/content/pgpetwll/naresh.xls”
    echo “This is an email message test”> $EMAILMESSAGE
    echo “This is email text” >>$EMAILMESSAGE
    # send an email using /bin/mail
    /bin/mail -s “$SUBJECT” “$EMAIL” < $EMAILMESSAGE

    Please help me out from this

  • Anirudha Feb 8, 2011, 5:16 am

    Hi,

    I want to fetch only file names from a remote server only for the last 2 months and I want to save those file names in a file format. Please help me in writing this shell script..

  • M. Anwar Feb 10, 2011, 10:03 am

    Anybody could help me to write script to send email from Solaris 10 system including attachment on scheduled time??

    Please…………………………

  • Senthil Jul 19, 2011, 2:08 pm

    AIX:/home/Mydir # ./testemail.sh
    This is a Test email
    TEST
    Cc:

    Can someone help me.. it wrote the script and specified the mail receivers id but at the end it’s asking for Cc. Is that i need to specify any e-mail address.

  • Ram Oct 3, 2011, 2:53 am

    Hi Mason,

    This is very simple..Thanks

  • Prafull Oct 3, 2011, 5:50 am

    Hi Vivek,

    I am having problem with the mail functionality. (On HP UNIX System)
    I am executing below statement from command prompt and properly getting mail in my inbox.
    mailx -s “sample subject-tested me” someone@email.com < /tmp/message.txt

    However, If I put the same statement within the shell script and executing the script, its not working at all. What may be the reason. How I can debug the cause of this failure.

    Please help.

    Thanks,

  • Manoj Nov 14, 2011, 6:20 am

    yes you missed something
    “$EMAILMESSAGE” in last line

    /bin/mail -s “$SUBJECT” “$EMAIL” “$EMAILMESSAGE”

    then enter

  • james Jan 24, 2012, 11:34 am

    I like mutt.

    > echo “hello” | mutt somebody@somewhere.com -a $linux.tgz -s “Linux code”
    or
    > cat RESULT_FILE | mutt somebody@somewhere.com -a $results.tgz -s “Test results”

  • Nick Jan 30, 2012, 4:57 pm

    I am trying to write a script that will send multiple, individual emails. I will have a delimited file with the email address and message text for each email . I need to loop through this file and send an email for each line. Can this be done? How do I update the Email Variables to do that?

  • Sanjeev Feb 6, 2012, 7:42 am

    I’m using Bourne shell and i’m not able to able to send emails to an externai mail id…. For eg., i sent an email to my personal mail id, but it did not turn up in my inbox. And i got a mail from mailer daemon in the file var/mai/root sayind dat it’s “unable to relay” to my personal mail id…… Plz help……

  • Pawan Feb 24, 2012, 8:57 am

    Thanks, This script works perfectly.

    Amazing.

  • Arizuddin Mar 12, 2012, 5:01 am

    Hi
    I want to receive an alert, when any administrator has executed Oracle related key shell script. How to do the setup for this?

    Help me.
    Arizuddin

  • Anar Jul 3, 2012, 7:50 am

    Hi I wanna script for ping host or ip alive or not alive and send mail abut this result

    thanks

  • shaggy Sep 13, 2012, 12:20 am

    How about putting this at the end of a bash file so it emails an attachment? My script would run and dump the output into > /file.txt How can I paste this script to attach the file and email it or grab the console output and email that instead of an attachment?

  • Anonymous Sep 15, 2012, 11:42 am

    How can we get the output of a query in html table so that it can be sent through mail in shell script

  • Melvin Sep 18, 2012, 9:29 pm

    Works fine! Thanks

  • bruma george Oct 24, 2012, 2:30 pm

    Hello admin.script not working,What can I do?

    Thanks

  • jason Dec 25, 2012, 7:24 pm

    sir, This script runs successfully ! but i am not recieving any mails in my account ! plz help ! :D

  • jason Dec 25, 2012, 7:26 pm

    sir, This script runs successfully ! but i am not recieving any mails in my account ! plz help ! :D

  • Ramesh Jan 14, 2013, 4:00 pm

    its not working

  • nihilus Feb 7, 2013, 9:12 am

    This breaks as soon as the input contains a char not in ASCII. I am currently looking for sending correct emails from command line, but this command seems to process the text byte by byte which is not correct if it is not ASCII.

  • nihilus Feb 7, 2013, 9:18 am

    One easy way around the issue with unicode is to specify the correct encoding. If the current locale uses UTF, adding
    -a "Content-Type: text/plain; charset=UTF-8"
    to mail seems to do the trick.

Leave a Comment