Skip to main content

Send mail with a BASH Shell Script

·252 words·2 mins· ·
General Features Bash Shell Scripts
Ariejan de Vroom
Author
Ariejan de Vroom
Jack of all Trades, Professional Software Craftsman

Like any good programmer, I try to automate the crap out of everything. If you have to do it more than once, I try to write a script for it.

This time I want to show you how you can easily send an e-mail from a BASH script. The idea is that you want the script to send out an email to notify a user that something has happened.

We’re going to use the GNU Mail utility here. The basic syntax to send an email is like this:

/usr/bin/mail -s "Subject" someone@example.org < message.txt

The trick when using this in a shell script is creating and using the message.txt file correctly.

Let’s setup the basis first:

#!/bin/bash
SUBJECT="Automated Security Alert"
TO="alarms@ariejan.net"
MESSAGE="/tmp/message.txt"

/usr/bin/mail -s "$SUBJECT" "$TO" < $MESSAGE

All we need to do now is create the message. In this example we’re going to notify the receiver that something happened at a certain time. We can use the append (») operator to add text to the message file. Afterwards, we must remove the temporary message file, of course. The complete script now becomes:

#!/bin/bash
SUBJECT="Automated Security Alert"
TO="alarms@ariejan.net"
MESSAGE="/tmp/message.txt"

echo "Security breached!" >> $MESSAGE
echo "Time: `date`" >> $MESSAGE

/usr/bin/mail -s "$SUBJECT" "$TO" < $MESSAGE

rm $MESSAGE

The email will contain the a timestamp from when the mail was sent.

This method is great for letting an administrator now if something happened. Maybe you need to check if your webserver is up and running. This script can an administrator about the issue.

Related

Find and Replace with a MySQL Query
·135 words·1 min
General Databases Features MySQL
Ultimate List of Ruby Resources
·214 words·2 mins
General Web Development RubyOnRails Features Lists Ruby
Trac, WebAdmin plugin and global configuration
·383 words·2 mins
General Features Linux Ubuntu Trac