In this article we’re going to take a look at how you can have Linux trigger an email alert once a certain condition has been met. We’re assuming you’re an intermediate or advanced user – which you should be, if you’re looking to set up email alerts on Linux – and that you have the mail client installed already.
Having an alert sent to you through email can be very useful. For example, if you have a large build being done in the background, it makes no sense to wait around for the process to finish. In such cases, you can have Linux send you a message once the build is done. It saves you a lot of time. You can also have an email alert sent to you at a certain time. If you have an engagement in the evening, you can program it into Linux so you don’t forget!
First, let’s take a quick look at how you can send an email to yourself. The command for it is “
mailx” or “
You can also attach a file to this, if you want
Getting Linux to Trigger an Email Alert
Now, we can couple the command we used above with a conditional statement. This means that when the condition is satisfied, an email will be sent to you. Enter the following in the command line:
This can be done in another way too. Let’s look at another example. What if you were waiting for a server to respond? You can either keep typing commands in the shell or you can have an email alert delivered to you when the server wakes up. You can use this command, for example:
If you look closely, the code above is an infinite loop. When your system pings the server (servername), the loop gets broken and a mail will be sent to you. You don’t need to wait until a server has booted up or updated.
If you’re worried about system resources being spent, you can put the system to sleep by amending the command a little:
In this case, the computer will sleep for 200 seconds before it executes a new cycle. You also get a regular alert (that the loop is working) every few seconds this way.
You can put virtually any shell command as the condition (so long as it’s sensible and doesn’t overload your system):
What if you wanted to email yourself on a certain date at a certain time? You can change the command above a little like this:
If you were looking to receive notifications whenever you receive an email on your Linux system, you can install applications that support email notifications. Two of the more popular applications are PopTray Minus and Mail Notification.
You can experiment with the commands given above. The premise is simple - just design a condition statement which, when met, will trigger an email alert. If you need more info or help on how to use mailx, simply type "
mailx --help"to display the help list.