Mac: How to send text messages from the command line and shell scripts

Today I learned that on macOS systems you can send text messages from the command line and shell scripts. You can send text messages to phone numbers and email addresses, and the only restriction I’m aware of is that the contact has to be a known Messages/iMessage contact.

A Mac shell script to send a text message to a phone number

Here’s a shell script to send a text message to a known phone number:

#!/bin/bash

# the phone number and message
PHONE_NUMBER="9078675309"
MESSAGE="This is a test text message from the command line."

# a bit of applescript to send the message
osascript <<EOF
tell application "Messages"
    set msgService to 1st service whose service type = iMessage
    set msgBuddy to buddy "$PHONE_NUMBER" of msgService
    send "$MESSAGE" to msgBuddy
end tell
EOF

A Mac shell script to send a text message to an email address

Here’s a shell script to send a text message to a known email address:

#!/bin/bash

# the email address and message
EMAIL_ADDRESS="coyote@acme.com"
MESSAGE="This is a test message from the command line!"

# send the message with a bit of AppleScript
osascript <<EOF
tell application "Messages"
    set targetService to 1st service whose service type = iMessage
    set targetBuddy to buddy "$EMAIL_ADDRESS" of targetService
    send "$MESSAGE" to targetBuddy
end tell
EOF

All you have to do is:

  • Make your scripts executable with chmod +x
  • Run the script the first time, and choose the correct option on the dialog that comes up to allow permission for this

Once you’ve done that, you can send text messages from your macOS command line and Mac/Unix shell scripts.