Sub topic 16
Light automation with AppleScript and the shell
This chapter assumes you have read the earlier chapters on accounts, Mail, Calendar, Contacts, and privacy permissions. You should be comfortable opening Terminal and Script Editor, and you should know which accounts are set up in System Settings. Automation here is deliberately light. You will read data from the three apps and hand off small tasks to them.
Two ways to talk to the apps
macOS offers two routes that fit this chapter.
- AppleScript talks to a running app through its scripting dictionary. Mail, Calendar, and Contacts each publish one. You can read properties such as account names, and you can create or change items.
- The shell uses commands like
openandosascript. Theopencommand hands a URL or file to the default app. Theosascriptcommand runs AppleScript from Terminal, so you can combine both routes in one shell script.
The two routes differ in power. AppleScript can inspect and change data inside an app. The shell with open only starts a task, such as drafting a message, and the app takes over from there.
Permissions come first
Scripts that control another app need your approval. The first time a script targets Mail, macOS asks whether the app running the script may control Mail. Approve it, and the choice is stored in System Settings under Privacy & Security, in the Automation section. Each pair of apps has its own entry. For example, Terminal controlling Calendar is a separate entry from Script Editor controlling Calendar.
Reading calendar or contact data can also involve the Calendars and Contacts entries in Privacy & Security. If you dismissed a prompt by mistake, the script fails until you turn the permission back on in that settings pane.
Read-only first: confirming that scripting works
Start with commands that only read. They cannot change or delete anything, so they are a safe way to check permissions.
tell application "Mail"
get name of every account
end tellThe tell block addresses one app. Inside it, get name of every account asks for the name property of each account object. The result is a list of strings, such as {"iCloud", "Work"}. These are the descriptions you see in System Settings, which are not necessarily the email addresses.
The same pattern works for Calendar and Contacts.
tell application "Calendar"
get name of every calendar
end telltell application "Contacts"
get name of every group
end tellThe calendar names this script returns are exact strings. Later scripts must match them character for character, including capitals and spaces. Copy the name from the result instead of retyping it. If you have two calendars with the same name in different accounts, the script finds the first one it meets, which may not be the one you want.
Running AppleScript from the shell
Script Editor is convenient for trying things. For repeatable work, run the same code from Terminal with osascript. The -e option takes one line of script, and you can repeat it for several lines.
osascript -e 'tell application "Calendar" to get name of every calendar'The one-line form tell application "X" to ... is equivalent to a full tell block. For longer scripts, save the code in a file, for example calendars.applescript, and run it.
osascript calendars.applescriptBy default osascript prints results in a readable form, with list items separated by commas. If you want to process the output in another command, split it on the comma and space, or return one item per line from the script itself.
tell application "Calendar"
set calNames to name of every calendar
end tell
set AppleScript's text item delimiters to linefeed
return calNames as textHere text item delimiters controls what goes between list items when the list becomes text. Setting it to linefeed gives one name per line, which works well with tools such as grep and sort. Reset it afterwards if the rest of your script relies on the default.
Handing off a task with the shell
The open command does not read data. It starts a task in the default app for a given URL scheme or file type.
open "mailto:[email protected]?subject=Hello"This opens a new message in your default mail app, with the recipient and subject already filled in. The message is not sent. You review it and click Send. That makes mailto: a safe handoff, because a person confirms every message.
Some details that matter:
- The default mail app is set in Mail settings. If you changed it to another app, that app opens instead.
- Spaces and special characters in the subject must be percent-encoded, so
Hello therebecomesHello%20there. - You can add
&body=after the subject for body text, using the same encoding rules.
open "mailto:[email protected]?subject=Weekly%20report&body=Draft%20attached."open also works on files. A file with the .vcf extension opens in Contacts, and a file with the .ics extension opens in Calendar, which then offers to add it. Both are covered in the chapters on vCard files and invitations.
BEGIN:VCARD
VERSION:3.0
FN:Ada Example
N:Example;Ada;;;
EMAIL;TYPE=INTERNET:[email protected]
TEL;TYPE=CELL:+1-555-0100
END:VCARDSave this text as ada.vcf, then run open ada.vcf. Contacts shows the card and asks whether to import it. The FN line is the formatted display name. The N line splits the name into family, given, and other parts, in that order.
Choosing between the two routes
| Task | Better tool | Reason |
|---|---|---|
| List accounts, calendars, or groups | AppleScript | Reads data inside the app |
| Draft an email for review | `open "mailto:..."` | No Automation permission needed, and a person sends it |
| Import a card or event file | `open file` | The app's own import dialog handles it |
| Run the same check every morning | `osascript` in a shell script | Can be scheduled and combined with other commands |
Common errors and how to read them
| Message or symptom | Likely cause | Fix |
|---|---|---|
| Not authorized to send Apple events (error -1743) | Automation permission denied | Turn the app pair on in Privacy & Security, Automation |
| Can't get calendar "Work" (error -1728) | The name does not match exactly | Run the list script and copy the name |
| Script hangs on first run | A permission prompt is waiting behind another window | Find and answer the prompt, then run again |
| Empty list returned | The account is disabled or still syncing | Check Internet Accounts, then wait for sync |
| `mailto:` opens the wrong app | Another app is the default mail app | Change the default in Mail settings |
Scripts that use osascript from Terminal launch the target app if it is not running. Mail may therefore open and start fetching mail when you run a script. Add if application "Mail" is running then around your code when you want to avoid that.
if application "Mail" is running then
tell application "Mail"
get name of every account
end tell
else
return "Mail is not running"
end ifKeeping scripts safe
- Begin with
getcommands. Add commands that create or delete items only after the read-only version works. - Test changes on a throwaway calendar or a test contact group, not on your real data.
- Do not store passwords in scripts. The apps already hold account credentials, and a script has no need to see them.
- Keep scripts in a folder you back up, and add a comment at the top that says what each one does.
Exercise
A script containing tell application "Calendar" to get name of every calendar works in Script Editor but fails in Terminal with error -1743. Why, and what fixes it?
Show answer
Automation permission is granted per pair of apps. Script Editor controlling Calendar and Terminal controlling Calendar are separate entries. Terminal has not been approved, or was denied earlier. Open System Settings, go to Privacy & Security, then Automation, and turn on Calendar under Terminal. Then run the script again.
Exercise
Write a shell command that opens a new draft addressed to [email protected] with the subject "Meeting notes". Explain why this command needs no Automation permission.
Show answer
open "mailto:[email protected]?subject=Meeting%20notes". The command only passes a URL to the default mail app, and does not send Apple events to control it. The draft is unsent, so you review it and click Send yourself.