The Ultimate Beginner’s Guide To AppleScript

The Ultimate Beginner’s Guide To AppleScript

Tutorial Details
  • Topics: AppleScript, Automation
  • Difficulty: Beginner
  • Estimated Completion Time: 30 Minutes

This is the first post in a new series that revisits some of our readers’ favorite posts from the past that still contain awesome and relevant information that you might find useful. This post was originally published on July 7, 2009.

The best part about AppleScript is that you don’t have to be a genius programmer to use it. In fact, you don’t have to have any programming experience whatsoever. This article will show you how to write an AppleScript for nearly any application using the simple instructions that come hidden within each app’s framework. Intrigued? Read on!


What is AppleScript?

AppleScript is a powerful scripting language that comes built-in to OS X. The principal use for AppleScript is the automation of tasks that are normally repetitious and time consuming. For instance, as a freelancer, I hate creating invoices every week for my various clients. To solve this problem I wrote an AppleScript that reads the hours that I log into iCal, creates an invoice in Microsoft Excel based on those hours, and emails the invoices to my clients. All with the click of a button!

applescript
The Main Window

Getting Started: The Tell Block

To create an AppleScript, open the application “Script Editor” located inside the AppleScript folder within the Applications folder. You should see a simple window containing a large text field with a strip of buttons along the top. Inside the text field type the following code:

tell application "Finder"
	display dialog "Hello World"
end tell

AppleScript attempts to use plain English wherever possible to make coding extremely simple. Most commands in AppleScript are located inside a “tell block”. It’s called a “tell block” because you are “telling” a given application what you want it to do. For instance, the code above is telling the Finder to display a dialog window containing the words “Hello World”. After you are finished with a command or string of commands for a given application, you end the block with “end tell”.

Always remember to end your tell blocks correctly or the code will not compile!

After you are done entering the code above, click on the “Compile” hammer icon. If your syntax is correct, your code will automatically format and colorize. If you have made an error, Script Editor will highlight the problematic area and give you a message about what it thinks might have gone wrong. Here is a quick reference to the various colors you’ll see in your compiled code (found in Script Editor>Preferences).

applescript
Color Guide

After your code has compiled, click on the “Run” button. You should see the following dialog:

applescript
Hello World

Now click the “OK” button and look at the bottom of your Script Editor window. When you run a script, Script Editor tells you what the result was, or what was “returned”. In this case it’s telling you that the “OK” button was clicked.

applescript
The OK Return

Declaring Variables

Variables are essentially the same in every programming language. They provide an easy way to access and manipulate lots of information in a compact snippet of code. Creating or “declaring” variables is different for every language. In AppleScript you declare variables as follows:

set theString to "Hello World"
tell application "Finder"
	display dialog theString
end tell

There are several things to note about the previous example. First, notice that variables are declared using the “set” and “to” commands. By doing this you are setting your variable name, in this case “theString”, to equal something, in this case the text “Hello World”. Many programming languages require that you state the type of variable you want in the declaration (integer, floating point, text, etc.). AppleScript however, is intelligent enough to work with your variables without any instruction about the format.

Also notice how I typed my variable name. You can’t have spaces in a variable name so it’s good practice to use camel case (theString) or the underscore method (the_string). It doesn’t really matter which method you choose, just make sure you’re consistent throughout your code. It’s also a good idea to give all your variables meaningful names. When you are looking another programmer’s code, it can be annoying to see variable names like “myVariable” that don’t give any indication as to what they are or what they will be used for.

Finally, notice that now that I’ve placed the text “Hello World” inside a variable, I can call that variable again and again throughout my code. Then if I later decide to change the text “Hello World” to “Good Morning Dave”, I only have to change the text on the line where I declared the variable.


Working with Variables

You can do all kinds of crazy things with variables, but since this is only meant to be a brief introduction to AppleScript, I’ll just show you a few. Type in the following code:

--Integer Variables
set theFirstNumber to 3
set the theSecondNumber to 2
--Variable Operations
set theAnswer to (theFirstNumber + theSecondNumber)
set theAnswer to (theAnswer + 1)
--String Variables
set theString to "3+2+1="
--Display Dialog
tell application "Finder"
	display dialog theString & theAnswer
end tell

You can compile your code quickly by pressing the “enter” key (not the return key). This is located on the ten key number pad on desktop computers and next to the “Command” key to the right of the space bar on laptops.

As your script becomes more complex, a bit of organization is in order. By typing two dashes “–” before a line of text, you can insert a comment. Use comments to separate and describe your sections of code for easy navigation. In this example I’ve created a string variable (text only) and a few integer variables. Notice that you can perform mathematical operations on variables. Here I’ve set “theFirstNumber” to equal three and “theSecondNumber” to equal two and then added them together in “theAnswer”.

Also notice that you can change a variable after it is declared. Immediately after setting “theAnswer” to the sum of “theFirstNumber” and “theSecondNumber” (resulting in 5), I changed the value of “theAnswer” by adding one to it (resulting in 6). If you run this script you should see the following result:

applescript
Some Basic Math

Again, this only scratches the surface of the kinds of operations you can perform on variables. For now you should just understand that a variable isn’t static. Much of the power of behind any programming language is the ability to manipulate variables to perform a wide variety of tasks.


The Key to it All: AppleScript Dictionaries

Though AppleScript itself has a wide range of commands that can be applied to any program or item in OS X, the developers of each application are tasked with adding full AppleScript support to their apps. What this means is that developers must write simple manuals for how to communicate with their applications through AppleScript. These manuals are called “Dictionaries”. To view a dictionary, go to File>Open Dictionary in Script Editor. Scroll down the list of applications, click on Mail and hit “OK”. You should see the following window:

applescript
The Mail Dictionary

The column on the left contains the available “Suites” of commands and items. When you click on a suite, you’ll see everything contained in the suite displayed below. You can narrow this preview by clicking in the second column, then again in the third. Suites contain commands (C with a circle) and classes (C with a square), classes contain properties (P) and elements (E). To understand how all this works, let’s use this dictionary to create a script.


Step 1: Create an Algorithm for Our Script

First we need an algorithm, which is a fancy way to say that we need write down exactly what our script will do. We want to create a script to compose and send an email. We’ll want to use variables to make it easy to change the message itself as well as who the message is sent to. As we write our algorithm, we need to keep in mind the way AppleScript works. Here are the steps I came up with:

  1. Create variables for the recipient, the recipient’s email address, the subject of the email, and the text for the body of the email.
  2. Create a variable that holds our new message along with its various properties
  3. Create the new message
  4. Send the new message

Step 2: Create Some Variables

We already know how to create variables holding text so we don’t even need the dictionary for step one. Here’s what the code looks like:

--Variables
set recipientName to "John Doe"
set recipientAddress to "nobody@nowhere.com"
set theSubject to "AppleScript Automated Email"
set theContent to "This email was created and sent using AppleScript!"

As you can see, we’ve just put placeholder text into the variables for the name and email address of the recipient as well as the subject and content of our message. You can change these to anything you’d like. Be sure to put your own email address in the recipientAddress variable so you can ensure that the the script is working properly when you receive the email.


Step 3: Create the Message Variable with the Mail Dictionary

Since we have no idea how to tell Mail to create a new message, this is where we need to refer to the AppleScript dictionary. If you click on “Standard Suite” you’ll see several common commands that come standard in AppleScript. Knowing that we want to “create” a new message, we just scroll through the options and find something equivalent. You’ll see there is no “create” command but about half way down there is a “make” command. That sounds perfect, so we now know to tell AppleScript we want to “make” something.

Next click on the “Mail” suite. We’ve already got our command (make) so scroll down past the commands (verbs) until you see the classes (nouns). The first class we come across is “outgoing message”, which is great because that’s exactly what we want! Now click on the “outgoing message” class and look at the available properties down below.

We need to plug in our variables for the recipient’s name, the recipient’s email address, the subject, and the contents of the message. In the list of properties there isn’t anything about the recipient but there are properties for subject and content. We now know the proper syntax to refer to these properties. Notice that the dictionary gives you the format to define the properties. For instance for the subject, we’ll type the word “subject” followed by a colon followed by the text of the subject.

applescript
Subject Content

Also in this suite you’ll find a “send” command, which we can use to send the message by simply typing “send”. We still need to know the proper syntax for the recipient’s name and email address. Since it’s not in this suite, click on the “Message” suite. About halfway down the list of classes we find “recipient”. Click on the recipient class and we see that once again, we can use plain English to refer to the properties of the recipient. We’ll simply type “name” and “address”.

You can use the search feature to hunt down properties, classes, elements and commands quickly.

Now we are ready to create our message variable using the syntax we’ve just learned. Here’s what the code looks like:

--Variables
set recipientName to "John Doe"
set recipientAddress to "nobody@nowhere.com"
set theSubject to "AppleScript Automated Email"
set theContent to "This email was created and sent using AppleScript!"
--Mail Tell Block
tell application "Mail"
--Create the message
set theMessage to make new outgoing message with properties {subject:theSubject, content:theContent, visible:true}
end tell

Notice I’ve created a tell block to enclose all the commands to the Mail application. Then I set a variable (theMessage) to “make” a new “outgoing message” with the properties discussed above. Also notice that sets of properties are always contained in brackets { }.


Step 4: Set the Recipient and Send the Message

Now that we’ve created our message variable, we need to call that variable and create a new message with the properties of theMessage. We also need to set the recipients and send the message. To do this, we’ll use a tell block on our variable. Here’s our finished script.

--Variables
set recipientName to "John Doe"
set recipientAddress to "nobody@nowhere.com"
set theSubject to "AppleScript Automated Email"
set theContent to "This email was created and sent using AppleScript!"
--Mail Tell Block
tell application "Mail"
	--Create the message
	set theMessage to make new outgoing message with properties {subject:theSubject, content:theContent, visible:true}
	--Set a recipient
	tell theMessage
		make new to recipient with properties {name:recipientName, address:recipientAddress}
		--Send the Message
		send
	end tell
end tell

First, we created a new copy of theMessage (which inherits all the properties we’ve put into it) and set it “to recipient with properties”. This tells Mail that we want to add a recipient with the following properties. Here we just used the syntax we learned before and the variables for the name and address of the recipient.

Finally, we invoked the “send” command to send our message. Notice that we have two tell blocks to close this time. Once you’ve compiled your code and fixed any errors hit the “Run”. Mail should automatically create and send the message. Tadaah! Check your sent folder to make sure everything worked.

applescript
Mail Message

Congratulations, you’ve created your first AppleScript! You can save it as a simple script that you can come back and edit or as an application that runs automatically when you open it.


Conclusion: Keep Learning

I hope this beginner’s guide has you thinking about all kinds of processes and tasks you’d like to automate. The syntax I’ve shown you along with the AppleScript Dictionaries will get you a long way. However, if you’re really interested in implementing AppleScript in a number of useful ways, you’ve got more reading to do. Apple provides lots of information all about AppleScript on their website. Here’s a good place to start.

Another website I’ve picked up a great deal from is T&B. It offers some really in-depth explanations and tutorials for you to follow (a little dated, but thorough and free). Please feel welcome to leave a comment and let us know if you found this tutorial helpful! What other AppleScript tips would you like to see covered in the future?

Josh Johnson is secondfret on Graphicriver
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Pingback: Darklg Web (darklgweb) 's status on Tuesday, 07-Jul-09 14:21:34 UTC - Identi.ca

  • http://www.newportharbor.com Steve

    Great Article. Followed right along and sent my first email message! You should write a series on AppleScript, it would be very helpful to learn some more. Also the link you have in the first paragraph of the conclusion goes to the Synium website. I think you want to redirect to: http://developer.apple.com/applescript/

    • Joshua Johnson
      Author

      That’s precisely where I was trying to link to… an old link got thrown in there instead. Good catch!

      • http://davidappleyard.net David Appleyard

        Fixed! Thanks :)

    • http://www.desktopcurtain.co.uk Desktop Curtain

      http://www.desktopcurtain.co.uk

      Free mac osx applescript application to hide all your desktop icons at a click of a button.

  • water.

    awesome

    • http://candiedcartel.com Candied Cartel

      at first I struggled a bit to install the applications, Apple now seems a breeze

  • Billy K

    You write “The best part about AppleScript is that you don’t have to be a genius programmer to use it. In fact, you don’t have to have any programming experience whatsoever. ”

    Well, that depends on what you want to do. You can do simple things without programming experience, just as you don’t need to be a mechanic to change the oil in your car. If you want to do more complex things, you *do* need programming experience. Which of course you can get by writing AppleScripts.

    My point is that many people using helpful and powerful tools such as AppleScript and Excel don’t realise that they are actually programming and that making complex scripts or Excel documents does require substantial programming skills if want you have a reliable result.

    Your invoicing script is a good example. Just think of the trouble someone could find himself in by using a poorly written automatic invoicing script which sends incorrect invoices or invoices the wrong clients. Properly designing and testing such a script is a programming task and should be approached as such.

    I don’t want to sound negative — AppleScript is a great tool — but like every tool it is no better than the craftsman using it.

    • Joshua Johnson
      Author

      I’m in complete agreement. AppleScript has many advanced features and I still get stumped at times. Sometimes seemingly routine tasks can take hundreds of lines of codes. The message I was trying to get across was that to “Get Started” (hence the article name) with Applescript, you need only poke around with the dictionaries to make some cool stuff happen. I know this because it’s exactly how I learned. However, now that I have a few programming languages under my belt I can do a LOT more with AppleScript. I merely sought to encourage non-programmers to take a shot at it :)

  • Jay

    Thank you for very useful article.
    Now i try create AppleScript for my Mail App to Encoding (Message > Text Encoding) my incoming mail. And i want to add that Script to Mail’s Rule for my future incoming message.
    And that’s not easy for me! ..

    Would you Please to show me how to do that ??

    Thank you.

  • Pingback: AppleScript Anleitung für Einsteiger – Mensch™ 2.0 - Nerdish by Nature

  • Pingback: The Ultimate Beginner’s Guide To AppleScript « AppStorm « Netcrema - creme de la social news via digg + delicious + stumpleupon + reddit

  • http://www.yummygum.nl Vince

    Great article. We will be exploring the advantages of AppleScript soon… Imagine automating the invoice process, we would love it… :D

  • Cheez

    Thank you for sharing this!

  • Aprozz

    That was exactly what I was looking for. I tried to write some AS before, but it never worked that good. And on the internet you just find realy tecnical information. I like this hands on tutorial.

    Thank you very much.

    PS. I’m looking forward to see more of AS tutorials… ;-)

  • http://www.hellopanos.co.uk Panos

    Thank you! this is great stuff! Keep up the great work!

  • Mary

    Thanks a lot for this tutorial. I already looked at AppleScript before but stuck to Automator ( which is applescript but simplier ) and left it since I couldn’t do what I wanted.
    Now I know where to look.
    I would never, ever thought there was a dictionnary !!

  • Pingback: Great beginner’s guide to AppleScript | Techdare

  • Pingback: Great beginner’s guide to AppleScript | iJustApple

  • Pingback: RSS News Portal » Great beginner’s guide to AppleScript

  • Pingback: Apple Bloog » Blog Archive » Great beginner’s guide to AppleScript

  • Pingback: Great beginner’s guide to AppleScript | oQlz Blog

  • Pingback: Great beginner’s guide to AppleScript | iAppleShare.com - Know everything about Apple products.

  • Pingback: Great beginner’s guide to AppleScript « Info for Life!

  • Pingback: Great beginner’s guide to AppleScript | Mac

  • Pingback: AAPL Blog » Blog Archive » Great beginner’s guide to AppleScript

  • Pingback: Apple News » Great beginner’s guide to AppleScript

  • Tom

    I’ve dabbled in AppleScript a few times, and this is a good intro. What i’d like to see is an exploration of how to work with existing items in various apps. For example, can I create a script that works with the selected iTunes tracks or with a calendar named “Work”? It seems to me that, even with the dictionary, that’s the hardest part of getting any AppleScript project going.

    Also, I know that I can write scripts to run as an iCal alarm or a Mail rule, and it would be great to see some examples.

  • Pingback: Apple-Overload! » Great beginner’s guide to AppleScript

  • Eric

    If this gets people’s attention, and they want to pursue the subject, the best book I’ve found so far is “Applescript 1-2-3″ by Sal Soghoian and BIll Cheesman. Sal’s in charge of Applescript at Apple and Bill Cheesman is the god of Applescript writing (and I hear he’s a pretty good attorney).

    The book is very clear, the examples really good (you can download them from the publisher) and it takes a very logical progression from basics to complex. I’ve learned more from this book since I got it (ordered it on Amazon in Oct 2003 and it finally arrived March 2009), than from all the books and web pages before it.

    And I should add, if you want to be a power Applescripter, there is no substitute for Script Debugger. (Quite expensive, but very much worth it.) It lets you look inside Applications and dig out references and values that help you figure out how to write your scripts. (And has a pretty good education/non-profit discount.)

    BTW, I have no connection to this book or LateNight Software, except for being a very happy camper in both counts. I’ve automated things at work that have will save hundreds of hours of manual processing of photos, controlling Filemaker Pro, Extensis Portfolio 9, and building XML files, etc. They’re both worth twice the price!

    • Adolfo Ruiz

      Complete agree but I’m not sure that ScriptDebugger works under Lion (last release was in 2009 for Leopard). I’m satisfied enough with the built in Apple Script editor.
      I would like to add to the Sal’s 1,2,3 appleScript book, which by the way you can find at Safari Books On Line and alternatively parts of it at Google Books, a very good one by Hamish Sanderson and Hanaan Rosenthal: Learn AppleScript (third edition in Apress).

      What I would like, Joshua, is to learn about the bridge AppleScript-ObjC and the real possibility that knowledge of AppleScript offers for really programming more then automation tasks and entertaining scripts. May be can you point a little bit on that direction?
      Thanks a lot for sharing

  • Pingback: Great beginner’s guide to AppleScript | PCDigita.com - Everything Technology

  • Pingback: Thursday Morning News | MacTalk Australia

  • Pingback: Macplus » Blog Archive » The Ultimate Beginner’s Guide To AppleScript « AppStorm

  • http://zachkrasner.com/July-7-2009 Zach Krasner

    Nice article, featured at my in yesterday’s issue of Zach Krasner Times

    • http://www.abbottpub.com books publications

      You have no idea how much I’m glad I found your site with this article …

  • OnTheTurtleLog

    This looks even dumber than SQL. By dumb I mean easy and simple. But still dumb. I’ll stick to writing Java apps on my PC.

    • http://www.twitter.com/secondfret Joshua Johnson
      Author

      Have fun with that. I’m fairly fluent in Java, it’s a pretty high level programming language and I commend for your devotion to it. However, Java is completely unnecessary for automating simple tasks (akin to using a fire hose to water the daisies). If you ever cross over to the enlightened world of Apple, read this article again and consider making a few “dumb” scripts to do some really neat stuff :)

  • John

    Hi,
    I’ve followed the tutorial through (many many thanks for this, it’s the best I’ve come across). I;m brand new to the programming scene (I’m only 16), and have come across 1 snag when writing the code for Mail.

    On the line “make new to recipient with properties”, it comes up with an error, stating “Expected expression but found to”.

    Please can anybody help? Thanks for your time, and the guide :)

    • http://www.twitter.com/secondfret Joshua Johnson
      Author

      Hey there, I just copied and pasted my code from the article above to see if it would compile and it did… maybe you made a typo? Try to copy and paste the final code into a new window to see if it compiles. If it does, compare it line by line with your code to see where the error lies.

      • John

        Thanks for the reply. I found that the script compiled if I changed “make new” to “makenew” as well. I’ve got a 10 week summer break – can’t wait to get stuck into some programming :) Thanks again for the tutorial. Can’t wait for more :)

    • Another John

      Make sure you have all the appropriate “tell” statements. I kept encountering weird errors when I’d forget to wrap statements inside the “tell” lines that indicate where commands are being executed.

      (Incidentally, did anyone else notice that the code samples can’t be fully seen or copied on an iPhone? Frustrating.)

      • John

        Thanks for the advice, will keep in mind :)

        The first time I saw this was on my iPhone and I noticed that too. No matter, did all the coding on OS X anyway so it wasn’t any hassle :)

  • http://iphoneaday.wordpress.com Ed

    Oh my god I need a series of this on AppStorm nowwwwwwwwwwwwwwwwww

  • John

    Anyone please? I can’t wait to get stuck in with this haha… I’m not very experienced at troubleshooting, I guess it’s one of those things you get better at with practice.

    • greg

      John: I encountered the same error. (Quite frustrating as I’m an AppleScript newbie.) Just make the changes AppleScript is suggesting (delete the “to”, change the “:” to “,”, etc), then the script will compile

      • John

        Thanks for the reply Greg. As above, when I changed “make new” to “makenew” the script compiled too.. Thanks for the assistance :)

  • Pingback: links for 2009-07-09 « 個人的な雑記

  • Pingback: Prototype Log » Blog Archive » The Ultimate Beginner’s Guide To AppleScript

  • Pingback: The Ultimate Beginner’s Guide To AppleScript – MacAppStorm site offers free guide - New Beltane | Technology applied to make the World a Better Place to Live

  • Pingback: iPhone Software » Blog Archive » Great beginner's guide to AppleScript

  • Pingback: Shared Experiences » links for 2009-07-13

  • Pingback: x5.log » Blog Archive » AppleScript终极入门指南(上)

  • http://www.nburmandesign.com Multimedia Design

    I’ve been looking for a place to start getting into Applescript. Too many books are just daunting. I’d love to get Automator doing something useful.
    Thanks for the kick-start!

    • http://www.twitter.com/secondfret Joshua Johnson
      Author

      My beginner’s guide to Automator is coming soon! Keep checking back.

  • Pingback: Use iCal to tweet automatically | birdbathBUZZ

  • Pingback: x5.log

  • Tizzy

    Joshua, how did you get the line numbers to show up in your examples? Are you using a different editor then Script Editor for that?

  • Jim Smith

    Well done! Clearly written, organized, and well-illustrated. I’m speaking as a professional technical writer for over 30 years. You have done well at de-mystifying something that must intimidate most Mac users. I can recommend this to anyone.

  • Jonathan

    Thanks very much for theses guides. After reading this I’ve been able to write a script that opens Spotify and Airfoil at the same time, and streams audio from a specified application, in this case, Spotify. I’ve copied the script below in case anyone is interested!

    tell application “Spotify” to activate
    tell application “Airfoil” to activate

    tell application “Airfoil”
    set aSource to make new application source
    set application file of aSource to “/Applications/Spotify.app”
    set current audio source to aSource

    end tell

  • Clarkson

    You are seriously high if you think a Mac user with NO programming experience can do this easily. I support several Mac users – none of which would come even CLOSE to understanding this.

  • Alan

    This was really helpful and easy to follow. I’m pretty new to Mac and started leaning HTML and wanted to have a play with applescript and see what it was like. This article is exactly what a newbie needs.

    Thankyou kindly for sharing it.
    -Alan

  • Pingback: Mac Roundtable 2009.08.27 Episode #68 @ world news

  • Dave

    For any Applescript newbies (like myself) I had trouble finding Script Editor. On my Mac (with Snow Leopard) the app is actually named “Applescript Editor” and it is in the Applications/Utilities folder.

    • http://esaruoho.tumblr.com/ esaruoho

      If you’re in Finder, you can press CMD-Shift-U and you’ll be transported to the /Applications/Utilities -folder straight up. :)

  • professor brainstawm

    Thank you for getting me started!

    • http://www.growsyracuse.com Syracuse Business

      now is easier to understand….