Send mail bash script

Explains how to write a shell script to send an email from command prompt under Linux / UNIX operating systems.

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’ [email protected] 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="[email protected]"
# 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

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.

67 thoughts on “Send mail bash script”

  1. 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.

  2. 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.

  3. Another way is to use a “here” doc:

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

  4. 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?

  5. Do anybody know what i am doing wrong?

    script:

    #! /bin/sh
    SUBJECT=”SET-EMAIL-SUBJECT”
    EMAIL=”[email protected]
    EMAILMESSAGE=”pathtofile”

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

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

  6. 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

  7. 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

  8. You could try something like

    mail -s “mail subject” [email protected] -a “Reply-To: &[email protected]&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).

  9. 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 “[email protected]” -s “Some subject” -S smtp=some.smtp.server [email protected] < 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.”

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

  11. 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.

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

  13. 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.

  14. 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.

  15. 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
    }
  16. 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.

  17. 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 :)

  18. 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?

  19. 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

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

  21. 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 : [email protected]
    #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="[email protected],[email protected]"
      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
  22. Doug,
    Most linuxes should come with mktemp, which you could use to make a unique filename in the /tmp directory. $EMAILMESSAGE becomes:

    EMAILMESSAGE=`mktemp`

  23. 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

  24. 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.

  25. 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.

  26. 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.

  27. 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.

  28. hi,
    i used the same code but unable to get the xls attachement.
    This is my code—————
    SUBJECT=”SET-EMAIL-SUBJECT”
    # Email To ?
    EMAIL=”[email protected]
    # 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

  29. 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..

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

    Please…………………………

  31. 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.

  32. 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” [email protected] < /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,

  33. yes you missed something
    “$EMAILMESSAGE” in last line

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

    then enter

  34. 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?

  35. 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……

  36. 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

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

    thanks

  38. 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?

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

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

  41. 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.

  42. 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.

  43. can anybody help me to write script in ubuntu to spy if any folder undergoes any changes or any addition in folder and if changes occur automatically mail is sent

Leave a Reply to Pradip

Your email address will not be published. Required fields are marked *