Saturday, October 23, 2010

Sending email using Command line + Scripting with example


Trial 1:

mail -s "This is a subject" john.doe@test.net < /root/myBodyFile

This simple command will send the email to john.doe@test.net with the subject "This is a subject" and body with the content of the file /root/myBodyFile

Trial 2:

You could check if your linux machine delievered the message to john doe or not.

# mail

If you see any MAILER-DAEMON@ , check if it is for john.doe@test.net (i.e email recepient) or not.

There could be various possible issues.

In my case I am using PostFix as my MTA.
I have configured mailrelayhost for my MTA.

For postfix, you can go to

#vi /etc/postfix/main.ca
------
-----
mailrelayhost= < specify ur mailrelay host or IP address of your mail server >
-----
-----

And also make sure that your linux machine's IP address is allowed to send email using email server (contact your email server administrator). He will add IP address of your linux machine as trusted host in his email server

Trail 3:

I would like to create alias so that I can send email to the group of people. It's easy.

Login as a root in your linux machine

#vi /etc/aliases
-----
----
#myEmailGroup: List of all emails separated by comma
-----
-----
ServerAlert: user1@gmail.com,user2@hotmail.com,214000000@txt.att.net
-----
-----

Next step is to load all the aliases

#newaliases

#echo $?
If it returns 0, then above command was executed succesfully


Finally you can send email to the group of users by

#mail -s "Hi.. all of you" ServerAlert < /root/myBodyFile


Application of email alert for the Asterisk PRI monitoring:

1. Create the script file

#vi astPRIcontrol.sh
#!/bin/bash
#author DShah erdevendra@gmail.com
#created on 10/22/10
#This script checks the PRI status; If PRI is down, it pages the admins

pristatus=echo /usr/sbin/asterisk -rx "pri show spans" |grep -i down

if [ -z $pristatus ]
then
#echo "PRI up"
notify=0
else
#echo "PRI down"
notify=1
fi

if [ $notify -eq 1 ]
then
mail -s " PRI down" Server_Alert < /root/pristatus

fi


2. Change the permission (make the script executable)

#chmod 700 /root/astPRIstatus.sh

3. Create a file called /root/pristatus

#vi /root/pristatus
PRI at asterisk server is down

4. Add the script file in crontab: it runs the script every minute

#crontab -e

*/1 * * * * bash /root/astPRIstatus.sh >/dev/null