Send email on shutdown (CentOS 7)

Orla Nicole
2 min readNov 10, 2020

We will use postfix to achieve this. In this example emails will be relayed through another existing mail server in your local network.

1. Remove sendmail and install postfix.

yum remove sendmail
yum install postfix

2. Set postfix as the default Mail Transfer Agent.

alternatives — set mta /usr/sbin/postfix

If you get this error:/usr/sbin/postfix has not been configured as an alternative for mtathen run this command:

alternatives — set mta /usr/sbin/sendmail.postfix

3. Configure postfix to route emails through existing smtp server

postconf -e 'relayhost ='

4. Restart postfix and enable the service.

service postfix restart
service postfix status
chkconfig postfix on

5. Verify that you can send emails ok

/usr/bin/printf "Test email message body" | mail -s "Test email subject message" -S "from=Sender Name <>"

6. Create the script and unit file for systemd

Create a file called /usr/local/bin/ and copy and paste the script below and replace these values:

  • EMAILS : the emails you wish to send to.
  • from=Your Chosen Name <> : the sender name and sender email you wish to appear on the email.
SUBJECT="[$HOSTNAME] - Server $1"

if [ "$1" = startup ]
ACTION="started successfully at"
ACTION="is shutting down. The Shutdown process started at"

BODY="This is an automated message to notify you that %s %s.\n%s\n"
for email in $EMAILS
printf "$BODY" "$HOSTNAME" "$ACTION" "$(date)" | mail -s "${SUBJECT}" -S "from=Your Chosen Name <>" "$email"
postfix flush
Orla Nicole