I’m trying to have mailx send an email alert before system shutdown/reboot using systemd service:
My unit file executes properly on shutdown (logs shows the script being executed), but I never get the email.
My understanding is that mailx simply queues the messages for MTA (sendmail?) to be processed, hence I use sendmail.service in the After.
I’ve tested tons of different variations but can’t make it send the email. Seems like the email pipeline is interrupted at some point before my script gets executed.
pre-shutdown.sh in essence contains one command (simplified for brevity, and it works if I run it from terminal manually):
cat "$BODY" | mailx <params> to@domain.com
This is my Unit file:
[Unit]
Description=Send email alert just before shutdown
#Requires=network.target sendmail.service
After=network.target
After=sendmail.service
[Service]
Type=oneshot
RemainAfterExit=true
ExecStop=/path/pre-shutdown.sh
[Install]
WantedBy=multi-user.target
All your suggestions are valid, and should be taken into consideration. But as mentioned, in my case the script itself executes properly, it’s only the mail that is not being delivered.
I figured mailx by default spawns a child process for sendmail, and as such it ends before sendmail processes the mail in the queue. So, as the system is going down, the mail never gets delivered.
Solution
The solution in my case was to use the nifty mailx options that prevents mailx from exiting before the mail is sent:
mailx <params> -S sendwait to@domain.com
Here’s my working Unit file:
[Unit]
Description=Send email alert just before shutdown
After=network.target
[Service]
Type=oneshot
RemainAfterExit=true
ExecStop=/path/pre-shutdown.sh
[Install]
WantedBy=multi-user.target
Note that there’s no need for ExecStart=true, since RemainAfterExit=true takes care when there’s no ExecStart.
Also, I didn’t need sendmail.service at all – I’ve disabled sendmail.service altogether and it works.
Thanks for all the suggestions!
Hope this will save others some troubleshooting time.