Can I write a script to take an action right before the computer is going to go to sleep?
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