Sending a mail from a linux shell script
If the server is well configured, eg it has an up and running MTA, you can just use the mail command.
For instance, to send the content of a file, you can do this:
$ cat /path/to/file | mail -s "your subject" [email protected]
man mail
for more details.
If you want a clean and simple approach in bash, and you don't want to use cat
, echo
, etc., the simplest way would be:
mail -s "subject here" [email protected] <<< "message"
<<<
is used to redirect standard input. It's been a part of bash for a long time.
If both exim and ssmtp are running, you may enter into troubles. So if you just want to run a simple MTA, just to have a simple smtp client to send email notifications for insistance, you shall purge the eventually preinstalled MTA like exim or postfix first and reinstall ssmtp.
Then it's quite straight forward, configuring only 2 files (revaliases and ssmtp.conf) - See ssmtp doc - , and usage in your bash or bourne script is like :
#!/bin/sh
SUBJECT=$1
RECEIVER=$2
TEXT=$3
SERVER_NAME=$HOSTNAME
SENDER=$(whoami)
USER="noreply"
[[ -z $1 ]] && SUBJECT="Notification from $SENDER on server $SERVER_NAME"
[[ -z $2 ]] && RECEIVER="another_configured_email_address"
[[ -z $3 ]] && TEXT="no text content"
MAIL_TXT="Subject: $SUBJECT\nFrom: $SENDER\nTo: $RECEIVER\n\n$TEXT"
echo -e $MAIL_TXT | sendmail -t
exit $?
Obviously do not forget to open your firewall output to the smtp port (25).
Another option for in a bash script:
mailbody="Testmail via bash script"
echo "From: [email protected]" > /tmp/mailtest
echo "To: [email protected]" >> /tmp/mailtest
echo "Subject: Mailtest subject" >> /tmp/mailtest
echo "" >> /tmp/mailtest
echo $mailbody >> /tmp/mailtest
cat /tmp/mailtest | /usr/sbin/sendmail -t
- The file
/tmp/mailtest
is overwritten everytime this script is used. - The location of sendmail may differ per system.
- When using this in a cron script, you have to use the absolute path for the sendmail command.
Generally, you'd want to use mail
command to send your message using local MTA (that will either deliver it using SMTP to the destination or just forward it into some more powerful SMTP server, for example, at your ISP). If you don't have a local MTA (although it's a bit unusual for a UNIX-like system to omit one), you can either use some minimalistic MTA like ssmtp.
ssmtp
is quite easy to configure. Basically, you'll just need to specify where your provider's SMTP server is:
# The place where the mail goes. The actual machine name is required
# no MX records are consulted. Commonly mailhosts are named mail.domain.com
# The example will fit if you are in domain.com and you mailhub is so named.
mailhub=mail
Another option is to use one of myriads scripts that just connect to SMTP server directly and try to post a message there, such as Smtp-Auth-Email-Script, smtp-cli, SendEmail, etc.