Skip to content

Instantly share code, notes, and snippets.

@nathancrank
Last active January 10, 2025 23:22
Show Gist options
  • Save nathancrank/ff202d9e5cf30bd2bef7211d9a8d5ca6 to your computer and use it in GitHub Desktop.
Save nathancrank/ff202d9e5cf30bd2bef7211d9a8d5ca6 to your computer and use it in GitHub Desktop.
Sending iMessage via Terminal
function message() {
osascript - "$2" "$1" << EOF
on run {messageText, buddyName}
tell application "Messages" to send messageText to buddy buddyName
end run
EOF
}
alias replyto="message"
To send iMessages via the terminal, copy the script below into your .zshrc, .bashrc, .profile or whatever you use for shell config.
Obviously iMessages must be setup on your Mac already. This has been tested on macOS Sierra 10.12.4 Beta (16E144f) with ZSH, but should work back to at least 10.10 in theory. Apple may break this at any point because it's Apple and it doesn't seem to much like AppleScript anymore.
To send a message:
`message "Contact Name" "Message"`
or
`replyto "Contact name" "Message"`
example:
`message "John Doe" "Hello from Terminal"`
Known Issues:
- You can't message yourself. No idea why.
- Some contact lookups don't work as expected. Again, no idea why.
- Multiple iMessage accounts may not supported by this (check out http://stackoverflow.com/a/14469990 for an idea of how that might work)
Troubleshooting:
- Try a simple contact first that you know works well. Someone with just one contact method attached and a simple name.
- Add `echo $script` between lines 6 and 7 to see what the $script is concatenating to. It should read something like `tell application \"Messages\" to send \"message contents\" to buddy \"buddy name\"`
@hhas
Copy link

hhas commented Feb 2, 2017

Mashing code strings is evil and wrong, and a whole mess of quoting accidents waiting to happen. Pass any parameters as arguments to osascript as follows:

function message() {
osascript - "$1" "$2" << EOF
    on run {messageText, buddyName}
        tell application "Messages" to send messageText to buddy buddyName
    end run
EOF
}

@nathancrank
Copy link
Author

@hhas thanks, that makes osascript a lot easier to interact with than how I was approaching it. I only know enough shell script and AppleScript to be dangerous!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment