Send email before system shutdown (systemd)

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. in essence contains one command (simplified for brevity, and it works if I run it from terminal manually):

cat "$BODY" | mailx <params>

This is my Unit file:

Description=Send email alert just before shutdown sendmail.service



What am I missing?

Try to add a dummy start command:


Make sure to properly enable the service:

sudo chmod +x /path/
sudo systemctl daemon-reload
sudo systemctl --now enable unit_name

Check the journal:

sudo journalctl -u unit_name

Avoid using useless cats and pipes:

cmd << EOF

Make sure your script has a proper shebang.

Thanks vgaetera.

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.


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

Here’s my working Unit file:

Description=Send email alert just before shutdown



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.

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.