Programmatically sending an iMessage from OSX

For an internal service we had a need to programmatically send an Apple iMessage from a  Mac Mini when it had completed a sequence of certain tasks.

The advantage of an iMessage was that, unlike using an SMS Gateway, the costs are free. You just need an Apple phone that can be paired with the Mac Mini for use of the iMessage capability.

There is not a lot of documentation on the use of iMessage from Xcode and it does not seem to have an API but it turns out you can use it from AppleScript.

After firing up AppleScript you need to enter the following code:

on run {targetBuddyPhone, targetMessage}
tell application "Messages"
set targetService to 1st service whose service type = iMessage
set targetBuddy to buddy targetBuddyPhone of targetService
send targetMessage to targetBuddy
end tell
end run

Now save this out somewhere as sendiMessage and choose to save it as an App in the save as ‘type’.

You can now choose to run this App directly from the command line or indeed from within an Xcode App.

To run in from the command line you need to use the osascript command.

So to run an iMessage all you would need to do from the Terminal is:

osascript <MobNo> "Message"

Note When you are entering the correct mobile number the recipient has to have iMessage enabled otherwise it will fail, and you also have to miss the initial ‘0’ of the mobile number as it will get reformatted prior to sending with the country code.


  1. One other thing here. If you want to send an SME message rather than an iMessage the code will look something like this:

    launch application “Messages”
    tell application “Messages”
    activate –steal focus

    set targetBuddy to “MobileNo”
    set targetService to id of service “SMS”
    set textMessage to “YourMessage”

    set theBuddy to buddy targetBuddy of service id targetService
    send textMessage to theBuddy
    end tell

    OR something like:

    tell application “Messages”
    send “YourMessage” to buddy “MobileNo” of service “SMS”
    end tell

    depending whether you need to launch iMessage or not

  2. And the previous script which was using Skype as a cheap SMS relay:

    tell application “Skype”
    set message to send command “CREATE SMS OUTGOING MobileNo…” script name “SMS”
    set smsid to item 2 of every word of message
    send command “SET SMS ” & smsid & ” BODY ” & smstext script name “SMS”
    set result to send command “ALTER SMS ” & smsid & ” SEND” script name “SMS”
    display dialog “SMS send! Text: ” & smstext
    end tell

    You of course need to set the smatext variable

Leave a Reply