Send mail bash script

by admin on October 5, 2005 · 66 comments

in Shell scripting

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:

  1. #!/bin/bash
  2. # script to send simple email
  3. # email subject
  4. SUBJECT="SET-EMAIL-SUBJECT"
  5. # Email To ?
  6. EMAIL="admin@somewhere.com"
  7. # Email text/message
  8. EMAILMESSAGE="/tmp/emailmessage.txt"
  9. echo "This is an email message test"> $EMAILMESSAGE
  10. echo "This is email text" >>$EMAILMESSAGE
  11. # send an email using /bin/mail
  12. /bin/mail -s "$SUBJECT" "$EMAIL" < $EMAILMESSAGE
  13.  

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

{ 66 comments… read them below or add one }

1 Deepa January 2, 2006 at 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.

2 Andrew March 22, 2006 at 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.

3 Asela June 1, 2006 at 5:53 am

Thanx.

4 Mason February 13, 2007 at 10:40 pm

Another way is to use a “here” doc:

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

5 Mason February 13, 2007 at 10:41 pm

Another way is to use a “here” doc:

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

6 Walter March 8, 2007 at 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?

7 nixCraft March 8, 2007 at 10:54 am

You need to have forwarding smtp or working mail server.

8 sanya March 26, 2007 at 5:44 am

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

9 ted loud July 8, 2007 at 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”

10 ted loud July 8, 2007 at 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

11 vivek July 9, 2007 at 7:27 pm

What error do you get ?

12 Ron July 17, 2007 at 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

13 satish September 20, 2007 at 4:41 am

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

14 ZZarko March 4, 2008 at 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.

15 ZZarko March 4, 2008 at 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).

16 Mayur March 17, 2008 at 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.”

17 kjkl April 29, 2008 at 1:34 am

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

18 Gaurav May 6, 2008 at 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.

19 warez November 14, 2008 at 8:56 am

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

20 manik December 11, 2008 at 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.

21 Satheesh March 12, 2009 at 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.

22 Christopher Barry April 9, 2009 at 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
}
23 Granty May 1, 2009 at 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.

24 Kevin May 20, 2009 at 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 :)

25 asad July 3, 2009 at 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?

26 vivek July 5, 2009 at 4:34 am

Install mail command by tying:

sudo apt-get install mailutils
27 Alex July 19, 2009 at 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

28 Rajesh Arora July 27, 2009 at 5:56 am

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

29 prathamesh July 28, 2009 at 6:16 am

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

30 Pradip November 17, 2009 at 8:42 pm

Thanks !!!!

31 Doug Nakatomi November 18, 2009 at 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
32 Ken December 2, 2009 at 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`

33 enrique January 4, 2010 at 4:51 pm

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

34 Abdel January 14, 2010 at 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

35 Gerry March 18, 2010 at 12:12 am

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

36 kiran March 23, 2010 at 11:13 am

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

Regards
kiran

37 Rishabh May 26, 2010 at 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.

38 NUSTIAN June 2, 2010 at 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….

39 cem August 18, 2010 at 7:55 am

Great job man.

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

40 proghack October 13, 2010 at 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?

41 saravanan October 22, 2010 at 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.

42 Anonymous December 7, 2010 at 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.

43 Bard December 7, 2010 at 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.

44 Bard December 7, 2010 at 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.

45 naresh January 17, 2011 at 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

46 Anirudha February 8, 2011 at 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..

47 M. Anwar February 10, 2011 at 10:03 am

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

Please…………………………

48 Senthil July 19, 2011 at 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.

49 Ram October 3, 2011 at 2:53 am

Hi Mason,

This is very simple..Thanks

50 Prafull October 3, 2011 at 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,

51 Manoj November 14, 2011 at 6:20 am

yes you missed something
“$EMAILMESSAGE” in last line

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

then enter

52 james January 24, 2012 at 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”

53 Nick January 30, 2012 at 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?

54 Sanjeev February 6, 2012 at 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……

55 Pawan February 24, 2012 at 8:57 am

Thanks, This script works perfectly.

Amazing.

56 Arizuddin March 12, 2012 at 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

57 Anar July 3, 2012 at 7:50 am

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

thanks

58 shaggy September 13, 2012 at 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?

59 Anonymous September 15, 2012 at 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

60 Melvin September 18, 2012 at 9:29 pm

Works fine! Thanks

61 bruma george October 24, 2012 at 2:30 pm

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

Thanks

62 jason December 25, 2012 at 7:24 pm

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

63 jason December 25, 2012 at 7:26 pm

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

64 Ramesh January 14, 2013 at 4:00 pm

its not working

65 nihilus February 7, 2013 at 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.

66 nihilus February 7, 2013 at 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.

Previous post:

Next post: