Automatically disable unused accounts in Mail

Apr 02, '08 07:30:00AM

Contributed by: Anonymous

I use two email accounts, a personal Gmail (IMAP) account, and a work mail account (also IMAP). I can only access my work email from within my work network, as the server is not on the internet. So I whipped up the following AppleScript and Launch Agent to automatically disable my work account when I'm not at work.

Here's the AppleScript:

set run_result to (do shell script "ps ax|grep Mail.app|grep -v grep; echo -n")
if run_result = "-n" then
else
  set run_time to (do shell script "ps ax|grep Mail.app|grep -v grep|awk '{ print $4; }'")
  if run_time < "0:05.00" then
    tell application "Mail"
      try
        set ping_result to (do shell script "ping -c 1 -t 1 work-server")
        set enabled of account "Work" to true
      on error
        set enabled of account "Work" to false
      end try
    end tell
  end if
end if
The script checks to see if Mail is running, if it is, and it has not been running for longer than five seconds (of processor time), then it checks to see if the server work-server is available, and enables/disables the Mail account Work as appropriate. Obviously, you'll need to customize those values for your situation.

We also need a way to run this AppleScript automatically; for that we create a Launch Agent:
<dict>
  <key>Label</key>
  <string>net.checkmail.servers</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/bin/osascript</string>
    <string>/Users/username/path/to/applescript.scpt</string>
  </array>
  <key>WatchPaths</key>
  <array>
    <string>/Users/username/Library/Preferences/com.apple.mail.plist</string>
  </array>
</dict>
Save the above as net.checkmail.servers.plist in your user's Library » LaunchAgents folder, and it will run automatically when Mail's plist changes (which happens every time you launch Mail). Good luck!

[robg adds: I haven't tested this one, and note you'll need to edit both code snippets to match your setup.]

Comments (5)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20080327140749716