to send a daily email using a BASH shell script and cron, lets create a new file named daily_email.bash in the /etc/cron.daily directory.
[root@server1 ~]# cd /etc/cron.daily [root@server1 ~]# touch daily_email.bash
Add the following to the daily_email.sh file:
#!/bin/bash echo "Hello World" | mailx -s "Test Email" firstname.lastname@example.org
Let's manually run this script immediately, to ensure the email is sent:
[root@server1 ~]# bash daiy_email.bash
We can now update the BASH shell script with -A default to use the "default" function when sending emails. For instructions on how to use the -A default option, refer to how to send emails using mailx.
#!/bin/bash echo "Hello World" | mailx -s "Test Email" -A default email@example.com
Let's add comments and variables to our script.
#!/bin/bash ### VARIABLES ### recipient="firstname.lastname@example.org" subject="Test" ### SEND THE EMAIL ### printf "Hello World" | mailx -s "$subject" -A default $recipient
Let's schedule this email to be sent once a day, every day, at 5:00 am.
- In Terminal, enter crontab -e
- Press i to switch to insert mode
- Type 0 5 * * * bash /etc/cron.daily/example_email.sh
Note: 0 5 * * * represents 0 minutes, 5 hour, which equates to 5:00 am
- Press esc to swittch to command mode
- Press :w (to save)
- Press :q (to exit the vi editor)
To ensure this entry was saved:
[root@server1 ~]# crontab -l 0 5 * * * bash /etc/cron.daily/example_email.sh
Another server in LAN
If we have other CentOS email servers in the LAN, such as a Samba file server or Bind DNS server, we may want to create a BASH shell script with the mailx command to send a daily email. We can simply create the same daily_email.sh and crontab -e job on the other server as we did on the Postfix email server.