Send keystrokes to Mail app using Swift and Apple's Scripting Bridge

486 views Asked by At

I have a simple Swift app that needs to be able to control and send keystrokes to Mail.app. In pure AppleScript I'd do something like:

tell application "Mail"
  activate
  tell application "System Events" to keystroke "2" using command down

I've read Apple's Scripting Bridge Programming Guide and Communicating with Apps using AppleScript and Swift so I'm able to do this in Swift:

if let application = SBApplication(bundleIdentifier: "com.apple.Mail") {
  let mailApplication = application as MailApplication
  ...

What I don't understand is how I can replicate AppleScript's tell application "System Events" to keystroke ... functionality in Swift. "System Events" isn't an SBApplication so I can't get a reference to it the same way I can Mail.app.

1

There are 1 answers

0
foo On

No need to emulate keystrokes using GUI Scripting, which is brittle and flaky. While not exactly obvious from Mail’s dictionary (which is a mess), you can use AppleScript to select mailboxes directly.

The trick is to manipulate the selected messages property of the frontmost message viewer object.

The application class defines properties containing references to the standard mailboxes (inbox, outbox, drafts mailbox, etc):

tell application "Mail"
    set selected mailboxes of message viewer 1 to drafts mailbox
end tell

Or you can refer to custom mailboxes by name:

tell application "Mail"
    set selected mailboxes of message viewer 1 to mailbox "Foo"
end tell

(To find out the names of custom mailboxes, use tell application "Mail" to get name of every mailbox.)