Mail Archiving Service for Snow Leopard

Many moons ago, based on Delfim’s stuff and my previous tinkering, I came up with an original AppleScript to archive my e-mail under a Personal/Year/Quarter folder hierarchy, which was designed to be activated from either a Mail.app rule or via Mail Act-On.

Fast forward to 2009, and Snow Leopard’s new services architecture has prompted me to revise the script a bit. I have dropped it into an Automator service and bound it to ^P for Mail alone, adding Growl notifications to boot:

on run {input, parameters}

  tell application "Mail"
    set theMessages to selection
    set theCount to count of selection
    if theCount = 0 then return input
    repeat with thisMessage in theMessages
      set msgDate to date received of thisMessage
      set msgMonth to month of msgDate as integer
      set msgYear to year of msgDate as integer
      set msgQuarter to ((round ((msgMonth - 1) / 3) rounding down) + 1)
      set msgAccount to name of account of mailbox of thisMessage
      set msgMailbox to name of mailbox of thisMessage
      set mboxName to "Personal/" & msgYear & "/Q" & msgQuarter
      tell account "MobileMe"
        try
          set mbox to mailbox named mboxName
          get name of mbox
        on error
          make new mailbox with properties {name:mboxName}
          set mbox to mailbox named mboxName
        end try
        -- Important sanity check due to some IMAP servers deleting messages when moved atop themselves...
        set curmbox to (get mailbox of thisMessage)
        if mbox is not curmbox then
          move thisMessage to mbox
        end if
      end tell
    end repeat
  end tell
  
  tell application "GrowlHelperApp"
    if theCount > 1 then
      set suffix to "s"
    else
      set suffix to ""
    end if
    set the theNotification to {"Mail Notification"}
    register as application "Mail" all notifications theNotification default notifications theNotification icon of application "Mail"
    notify with name (item 1 of theNotification) title "Archiving " & theCount & " message" & suffix description "to " & mboxName application name "Mail"
  end tell
  return input
end run

(source)

To use this yourself, create a new service inside Automator, paste the source code into the Run AppleScript box, save it with whatever name it pleases you (I used “Archive to MobileMe”) and then go into System Preferences – Keyboard, create a new key binding for Mail and enter the that same name.