Friday, November 13, 2015

Email notification scheduling scripts on FreeBSD

Scripting is the best tool for any system administration,I had a system which is used to send notification email to clients, but we need these notification to be sent only on specific time, shell scripts help me to fully fill my needs by very few lines. I decided to share this script for any one wishing to schedule email sending on his system, my system use sendmail mail system and run on FreeBSD 7 operating system.

To achieve this I decided to design two scripts working as follows

a. Script one is used to stop the mail system at specific time.
b. Second script clean queued and deferred emails when the email system is down and start the email system.
c. Schedule the two scripts using the cron job to run on different time.

Below are steps for creating the scripts


a. Scripts 1

Change to root user and migrate to root directory, to create the scripts

sudo su
cd /root/ 

i. Create the file

vi stopsendmail.sh 

ii. Copy and paste the content below on created file

#!/bin/sh
/etc/rc.d/sendmail stop

And save the file. This script only stop sendmail mail system so that no any email will be sent.

iii. Make the script executable

chmod a+x stopsendmail.sh

b. Scripts 2

This second script clean the emails on the queue and any deffered email sent when mail system was done, and finally start mail system.

i. Creating the file

vi startsendmail.sh

ii. Copy and paste the content below on created file

#!/bin/sh
rm -rf /var/spool/mqueue/*
rm -rf /var/spool/clientmqueue/*
/etc/rc.d/sendmail start

iii. Make the script executable

chmod a+x startsendmail.sh

c. Create cron job to run the two scripts

Run the command below to open the cron file.

crontab -e

Copy and paste the following

# This Script stop the mail service at 17:45 Everyday
45 17 * * * /root/stopsendmail.sh
# This script start the mail service every 08:05 Evertday
05 8 * * * /root/startsendmail.sh

Your done, these two simple scripts will disable email system at one time and active it at the other time. If your using another system the commands and path may change a bit but semantics will be the same.


Hope it helps someone, if you face any challenge implementing the scripts drop the comment I will be happy to help.


Happy scripting and automation.