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:

  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 thoughts on “Send mail bash script

  1. shaggy

    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?

    Reply
  2. nihilus

    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.

    Reply
  3. nihilus

    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.

    Reply

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

What is 13 + 10 ?
Please leave these two fields as-is:
Solve the simple math (so we know that you are a human)