Search code examples
applescriptapple-mail

AppleScript move message to mailbox with Rules in Mail


I looked and looked but couldn't find an answer to this seemingly simple question (I'm also new to AppleScript). Basically, I just want a script that sets up a Rule and moves messages to mailbox "Foo" (a Mailbox in my IMAP account). Here's what I have:

tell application "Mail"
set newRule to make new rule at end of rules with properties {name:"Foo Internal",   enabled:true}
tell newRule
    make new rule condition at end of rule conditions with properties {rule type:any recipient, expression:"internal_foo@foo.com", qualifier:does contain value}
    set move message to mailbox "Foo"
end tell
end tell

I've tried various combinations of this line...

set move message to mailbox "Foo"

...including specifying the IMAP account, setting it to a variable, and so on. I'm not a programmer but I really want to script these rules cause I setup rules all the time at my job. Any help?


Solution

  • Your script fails because of two things:

    1. it omits to set the should move message property of the rule to true, which is needed for a move message action to actually “stick”;
    2. it does not define the object hierarchy of the target mailbox correctly: you will need both the account and the application context, as you are inside a tell block targeting the rule, not Mail.

    The following code:

    tell application "Mail"
        set newRule to make new rule at end of rules with properties {name:"Foo Internal", enabled:true, should move message:true}
        tell newRule
            make new rule condition at end of rule conditions with properties {rule type:any recipient, expression:"internal_foo@foo.com", qualifier:does contain value}
            set move message to (mailbox "Foo" of account "Bar" of application "Mail")
        end tell
    end tell
    

    will work in Mail 5.2 (stock as of OS X 10.7.4).