Send email on shutdown (CentOS 7)
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 mta’ then run this command:
alternatives — set mta /usr/sbin/sendmail.postfix
3. Configure postfix to route emails through existing smtp server
postconf -e 'relayhost = your-smtp-server.example.com'
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 <sender.name@example.com>" your.name@example.com
6. Create the script and unit file for systemd
Create a file called /usr/local/bin/mailme.sh
and copy and paste the script below and replace these values:
EMAILS
: the emails you wish to send to.from=Your Chosen Name <your.name@example.com>
: the sender name and sender email you wish to appear on the email.
#!/bin/shEMAILS="person1@example.com person2@example.com"
SUBJECT="[$HOSTNAME] - Server $1"
if [ "$1" = startup ]
then
ACTION="started successfully at"
else
ACTION="is shutting down. The Shutdown process started at"
fi
BODY="This is an automated message to notify you that %s %s.\n%s\n"for email in $EMAILS
do
printf "$BODY" "$HOSTNAME" "$ACTION" "$(date)" | mail -s "${SUBJECT}" -S "from=Your Chosen Name <your.name@example.com>" "$email"
postfix flush
done