Can I write a script to take an action right before the computer is going to go to sleep? I think my computer is randomly not syncing email correctly with Apple Mail, but it's only a problem when it wakes from sleep.

That issue is neither here nor there. What I'd like to do is write a script / something that will quit Apple Mail if it detects that the computer is going to sleep.

Ideally, there'd be a similar process to open Apple Mail upon waking from sleep, but that's less of an issue.

I tried looking for a system event library of some kind, but all I can find is fsevents (which I don't think has anything about sleep).

Thanks!
I suggest using a daemon like SleepWatcher. Once you’ve installed SleepWatcher (ref. the README included with it), you can run commands like the following.

/usr/local/sbin/sleepwatcher -s /path/to/sleepscript -w /path/to/wakeupscript


The script

#!/bin/sh
osascript -e 'quit app "Mail"'


will quit Mail, and the script

#!/bin/sh
open -a /Applications/Mail.app $1


will open it. You can save these as .sh files and reference them from sleepwatcher, but ensure you run chmod +x filename.sh on them before you try running them. Otherwise, OS X won’t recognize them as executable.

Now, you have two options for loading sleepwatcher: you can manually run it, you can configure a LaunchAgent to do so. I like the latter, so create a file in /Library/LaunchAgents/ named com.custom.mailfix.plist (the name is unimportant, but I recommend you keep the formatting, the “com” and the “plist”). The file’s contents should resemble the following.

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
&lt;key&gt;Label&lt;/key&gt;
&lt;string&gt;com.custom.mailfix.plist&lt;/string&gt;
&lt;key&gt;ProgramArguments&lt;/key&gt;
&lt;array&gt;
    &lt;string&gt;/usr/local/sbin/sleepwatcher&lt;/string&gt;
    &lt;string&gt;&lt;/string&gt;
    &lt;string&gt;-s /path/to/sleepscript&lt;/string&gt;
    &lt;string&gt;-w /path/to/wakescript&lt;/string&gt;
&lt;/array&gt;
&lt;key&gt;RunAtLoad&lt;/key&gt;
&lt;true/&gt;
&lt;key&gt;KeepAlive&lt;/key&gt;
&lt;true/&gt;
&lt;/dict&gt;
&lt;/plist&gt;


As before, replace the script paths with paths to your shell scripts. To tell OS X to launch this agent at startup, run

sudo launchctl load -w /Library/LaunchAgents/com.custom.mailfix.plist