Automatically file email in Mail based on sender's domain

Jan 30, '08 07:30:02AM

Contributed by: kaih

While I'm a huge fan of Smart Folders in Mail, I've possibly been abusing them and not filing my mail at all. Once I had around 10,000 messages in my inbox, I decided that it was time to do something about it. Ideally, I'd have multiple sub-folders, such as Clients and Vendors, and then in these folders, I'd have Client Name A, Client Name B... and Vendor Name A, Vendor Name B, etc.

Sorting through 10,000 emails and manually moving them wasn't my idea of fun -- even on a cold, rainy afternoon. Neither was creating a slew of individual rules for something like If from contains clientname.com then move message to mailbox Client Name. This seemed like a job for AppleScript! As my script-fu isn't as good as I would like it, I've resorted to having a single Sorted folder, and then within that are folders named with the relevant domain name -- eg clientname.com. Here's the script:

tell application "Mail"
  set theList to the selection as list
  repeat with theMessage in theList
    -- first we find the sender of the message
    set theSender to sender of theMessage as string
    -- now we strip off the sender's domain (everything after the "@")
    set oldDelimiters to AppleScript's text item delimiters
    set AppleScript's text item delimiters to {"@"}
    set theDomain to the second text item of theSender
    set AppleScript's text item delimiters to ""
    -- and strip the last character off the domain, as it will be a ">"
    set theDomain to get characters 1 through ((theDomain's length) - 1) of theDomain
    if theDomain = "" then set theDomain to "Undetermined"
    set targetMailbox to "Sorted/" & theDomain
    try
      move theMessage to mailbox targetMailbox of account "IMAP Account Name" of application "Mail"
    end try
  end repeat
end tell
I then have a single rule in Mail that applies this AppleScript to all incoming emails, and if I've created a folder with the relevant domain name, the emails will automatically end up in there. As it uses a try, if the folder doesn't exist, then the message isn't moved.

I would welcome additions to this script from the MacOSXHints community -- my thoughts to extend it would be to use AppleScript's ability to read plist files, and have a plist file containing clientname.com -> Client Name mappings, and also allow for it to be sorted with finer granularity -- eg, having Friends, Clients, Vendors folders. Such an interface could (relatively) easily be created in AppleScript Studio, and have Mail just call the script to do the heavy lifting.

Comments (6)


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