Bootstrap FreeKB - Bash (Scripting) - Send a daily email (cron)
Bash (Scripting) - Send a daily email (cron)

Updated:   |  Bash (Scripting) articles

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" user1@example.com

 

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 user1@example.com

 

Let's add comments and variables to our script.

#!/bin/bash

### VARIABLES ###
recipient="user1@example.com"
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.

  1. In Terminal, enter crontab -e
  2. Press i to switch to insert mode
  3. Type 0 5 * * * bash /etc/cron.daily/example_email.sh

Note: 0 5 * * * represents 0 minutes, 5 hour, which equates to 5:00 am

  1. Press esc to swittch to command mode
  2. Press :w (to save)
  3. 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.




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter e7c009 in the box below so that we can be sure you are a human.