[Script] Send e-mail from bash

, , 7 Comments



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 address, 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’ yourmail@test.com

Script

#!/bin/bash
# Subject
SUBJECT="EMAIL-SUBJECT"
# To
TOEMAIL="tomail@test.com"
# Message
EMAILMESSAGE="/home/user/message.txt"
echo "This is email text" >>$EMAILMESSAGE
# Sending email using /bin/mail
/bin/mail -s "$SUBJECT" "$TOEMAIL" < $EMAILMESSAGE
 

7 Responses

  1. juriad

    May 21, 2012 5:19 pm

    better is:

    /bin/mail -s "$SUBJECT" "$TOEMAIL" <<END
    This is email text
    END

    and you don’t need any extra file

    Reply
  2. Murdej Ukrutny

    May 21, 2012 10:01 pm

    or this if you need send program output:


    ( echo "foooo" ; ls ; ps ) | /bin/mail -s "$SUBJECT" "$TOEMAIL"

    Reply

Leave a Reply