Just like any proficient programmer, I’m all about automating tasks to the max. If it’s repetitive, count on me to whip up a script for it. Today, I’ll walk you through effortlessly sending an email from a BASH script. Picture this: your script needs to shoot off an email to alert a user about an event.

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="..."
MESSAGE="/tmp/message.txt"

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

Now, let’s craft the message. Here’s the plan: we’ll inform the recipient about an event that occurred at a specific time. To achieve this, we’ll employ the append (») operator to append text to the message file. Once done, naturally, we’ll tidy up by deleting the temporary message file. Here’s the refined script in full:

#!/bin/bash
SUBJECT="Automated Security Alert"
TO="..."
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 technique works wonders for keeping administrators informed when something occurs. Let’s say you need to monitor whether your web server is up and running smoothly. With this script, an administrator can promptly receive notifications about any arising issues.

My site is free of ads and trackers. Was this post helpful to you? Why not BuyMeACoffee