A script to move Mail message to IMAP folders

Apr 22, '04 09:13:00AM

Contributed by: mchang

Moving mail in Mail.app is very clumsy if you have lots of folders. You have to drag and drop, or control-click and select a folder. You need a lot of dexterity! One nice thing with the control-click method is that you can type the name of the mailbox when the list pops up. But, I have LOTS of folders, conveniently organized (via my Pine days) by email address (the root part, before the '@' symbol).

So, here's a piece of AppleScript to do that more automatically.

It works with a hardcoded IMAP account right now, so don't forget to read it and change that. Oh, and I store all my folders under a 'store' sub-folder on an "EE" account, also hardcoded here. I saved the following script as "Move email___ctl-cmd-s", which maps it to Ctrl-Cmd-S (this naming convention was also briefly covered in this hint). It's my first ever piece of AppleScript, so please be gentle. Updates will be posted to acmelab.org.

tell application "Mail"
  set theSelectedMessage to selection
  if (count of theSelectedMessage) is equal to 0 then
    display dialog ¬
    "Please select a message in Mail first, then run this script again."
  else if (count of theSelectedMessage) is equal to 1 then
    
    set thisMessage to item 1 of theSelectedMessage
    set theFrom to extract address from sender of thisMessage
    set astid to AppleScript's text item delimiters
    set AppleScript's text item delimiters to "@"
    set theEmailPart to item 1 of (every text item of theFrom)
    set AppleScript's text item delimiters to astid
    set theMailbox to "store/" & theEmailPart
    
    if the mailbox theMailbox of account "EE" exists then
      display dialog "Saving to:  EE | " & theMailbox
      if button returned of result = "OK" then
        tell application "Mail"
          move the selection to mailbox theMailbox of account "EE"
        end tell
      end if
    else
      display dialog theMailbox & ¬
      " does not exist on EE. Choose a new mailbox." default answer ""
      set theNewMailbox to (text returned of result) as string
      set theMailbox to "store/" & theNewMailbox
      if the mailbox theMailbox of account "EE" exists then
        tell application "Mail"
          move the selection to mailbox theMailbox of account "EE"
        end tell
      else
        display dialog "Mailbox " & theMailbox & ¬
        " does not exist." buttons "Cancel"
      end if
    end if
  else
    display dialog ¬
    "Please select only one message in Mail first, then run this script again."
  end if
end tell
[robg adds: I haven't tested this one myself...]

Comments (4)


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