As I’ve often said scripting Mail can be a chore as Apple left so much unexposed to Applescript that most IT folks really want to script. It’s annoying and probably reflects Apple’s ambivalence towards Applescript. Someone over at Stack Overflow had asked how to do it. I told them I had a half-finished script that was working for this. I ended up finding the time to finish it off finally.
I can’t promise this does everything. But it’ll at least get you in the right area. I know a lot of people want to do this and there aren’t a lot of guides on the net.
Basically what I do is open up a new smart mailbox using GUI scripting and then fill in the blanks. Now be aware I’m doing all this with Appscript and Python rather than pure Applescript. You should be able to figure out quickly what is going on though.
#!/usr/bin/python import os from appscript import * def makesmartmailbox(): M = app(u'Mail') SE = app(u'System Events').processes[u'Mail'] # Open New Smart Mailbox Sheet M.activate() SE.menu_bars.menu_bar_items[u'Mailbox'].menus.menu_items[u'New Smart Mailbox\u2026'].click() SMB = app(u'System Events').processes[u'Mail'].windows.sheets # Set Smart Mailbox Name SMB.text_fields.value.set(u'Test') # Set rules as any SMB.pop_up_buttons.click() SMB.pop_up_buttons.menus.menu_items.click() # switch to menu_items to click "all" # Select First Rule SMB.scroll_areas.pop_up_buttons.click() # Click "From" (2cd menu item) SMB.scroll_areas.pop_up_buttons.menus.menu_items.click() SMB.scroll_areas.text_fields.value.set(email@example.com') # Create Second Rule SMB.scroll_areas.buttons[u'add criterion'].click() # the new rule type is button 3 SMB.scroll_areas.pop_up_buttons.click() SMB.scroll_areas.pop_up_buttons.menus.menu_items.click() # the new text area is text field 2 SMB.scroll_areas.text_fields.value.set(firstname.lastname@example.org') # include messages from sent SMB.checkboxes[u'Include messages from Sent'].click() # Save the rule SMB.buttons[u'OK'].click() def test(): makesmartmailbox() if __name__ == '__main__': test()
The only tricky bits is finding the type of GUI object each button you want to press is it. The second trick is that for pop up buttons you have to first click the button, which creates a menu, and then select the menu item. Menu items in Applescript start at the number 1.
You’ll notice that new rules increment the popup button number by 2 as there are two popup buttons on each row. If you want to modify what rule type is picked just change the menu item number from 2 to some other number. Say 1 for “Entire Message.”
Now of course in a production script you’d put in various sorts of error checking. But this works well for me right now.