TweetFollow Us on Twitter

Introduction to Scripting Address Book

Volume Number: 21 (2005)
Issue Number: 10
Column Tag: Programming

AppleScript Essentials

Introduction to Scripting Address Book

by Benjamin S. Waldie

If you have a large number of contacts in your contact management application, then you are probably already aware that maintaining your existing contacts, adding new ones, removing outdated ones, etc., can quickly become a time consuming process. Yet again, AppleScript is ready to come to your rescue. Using AppleScript and Address Book in Mac OS X, you can begin to automate the process of adding and removing contacts, creating groups, and even more.

Throughout this article, we will discuss a number of techniques for automating aspects of Address Book in Mac OS X. Once you have an understanding of these basic techniques, you can begin combining them together, in order to automate your contact management workflow on a larger scale.

Figure 1 shows an example of an Address Book person, which has been created and added to a new group, all with AppleScript. The code that was used to create this entry and group was developed using the example code snippets that are provided throughout this article.

Please note that all code specified in this article was developed using Address Book version 4.0.2 in Mac OS X 10.4.x Tiger. Due to AppleScript terminology changes between versions of Address Book, some code may be slightly different, or may not function properly if you are using an older version of Address Book.

Working with People

Making a New Person

To create a new person in Address Book, use the make command, which can be found in the Standard Suite in Address Book's AppleScript dictionary. While using this command, you may also specify values for various properties of the person. This is demonstrated in the following code, which will create a new person, while assigning values to the first name, last name, organization, and job title properties.


Figure 1. A Person Created by a Script in a Specific Group

tell application "Address Book"		
   set thePerson to make new person with properties 
   {first name:"Ben", last name:"Waldie", organization:"Automated Workflows, 
   LLC", job title:"President"}
end tell
--> person id "778C4D8D-0A22-4918-A5B6-73361FFF8779:ABPerson" of application "Address Book"

The result of the make command is a reference to the newly created class. In the example code above, we have captured this reference in a variable named thePerson. This variable may now be referenced in future code, so that we may add email addresses, phone numbers, and more to the newly created person.

When writing code that interacts with Address Book, you might notice that Address Book's display is not immediately updated. Rather, it may take several seconds for the new person to appear. To force Address Book to update its display immediately, you may use the save addressbook command. For example:

save addressbook

It is good practice to use this command regularly in an Address Book script, in order to ensure that the display always shows the current information, as well as to prevent data loss in the unlikely event of an application crash.

Adding Email Addresses

In Address Book, email addresses, URL's, phone numbers, and addresses are not properties of a person. Rather, they are classes themselves, and are contained as elements of a person. The following example code demonstrates how to add an email address to a specified person.

make new email at end of emails of thePerson with properties 
{label:"Work", value:"applescriptguru@mac.com"}

In the example code above, the label property of the email address indicates the label text that will precede the email address in the person's address card in Address Book's interface. For example, an email address label might read "Work", "Home", "Other", etc. As you will see in some additional examples throughout this article, many other classes in Address Book also possess a label property.

Adding URL's

The method for adding a URL to a person is generally the same as that for adding an email address. The following example code demonstrates how to add a work URL to a specified person in Address Book.

make new url at end of urls of thePerson with properties 
{label:"Work", value:"http://www.automatedworkflows.com"}

Adding Phone Numbers

The following example code demonstrates how to add a work phone number to a specified person in Address Book. Again, as you can see, this code is generally the same as that for adding email addresses or URL's to a person.

make new phone at end of phones of thePerson with properties 
{label:"Work", value:"610.935.0652"}

Adding Addresses

Adding an address to a person is slightly different than the process of adding an email address, a URL, or a phone number. While you can still specify a label property for an address, addresses also possess many other properties. For example, in an address entry, you may specify a street, city, state, zip code, and more. The following example code demonstrates how to add a work address to a specified person in Address Book.

make new address at end of addresses of thePerson with properties 
{label:"Work", street:"123 Anystreet", city:"Anytown", state:"PA", zip:"99999"}

Finding a Person

In some cases, you may not actually want to create a person. Rather, you may want to locate an existing person. One way to access an existing person is by accessing the selection property of the Address Book application. This will return a list of any selected people. The following example code demonstrates how to retrieve the selection.

set thePeople to selection
--> {person id "778C4D8D-0A22-4918-A5B6-73361FFF8779:ABPerson" of application "Address Book"}

However, you may not always want to access the selected person or people. There may be times when you need to locate a person by name, or by another criteria. The following example code demonstrates how to search for specific people by retrieving a list of people matching a given last name.

set thePeople to every person whose last name = "Waldie"
--> {person id "778C4D8D-0A22-4918-A5B6-73361FFF8779:ABPerson" of application "Address Book"}

Retrieving Information for a Person

Once you have retrieved a list of people in Address Book, you will more than likely want to retrieve information about those people, such as their names, email addresses, etc. For starters, the following code demonstrates how you can retrieve a list of all properties of a specified person.

properties of (item 1 of thePeople)
--> {first name:"Ben", maiden name:missing value, 
id:"E9A1B78D-AE19-46D1-98A8-76ADB82E4C49:ABPerson", modification date:..

You may also retrieve the properties of specific elements of a person. For example, the following example code will retrieve properties of any email addresses of a specified person.

properties of emails of (item 1 of thePeople) -->
{{id:"9495797E-3942-4CA2-9EB7-A85CC1420A40", 
class:email, label:"work",value:"applescriptguru@mac.com"}}

Similar to the previous example code, the following example code demonstrates how to retrieve the properties of any phone numbers of a specified person.

properties of phones of (item 1 of thePeople) -->
{{id:"5D411959-09F0-4A65-82FA-01449FD50268", class:phone, label:"work", value:"610.935.0652"}}

Working with Groups

In Address Book, groups are also an important part of contact management. Groups allow you to organize your contacts into sets of contacts, all related in some manner of your choosing. Like people, groups in Address Book are also accessible via scripting.

Making a New Group

In a manner similar to that for creating a new person, the make command may be used to create a new group. For example:

set theGroup to make new group with properties {name:"My Group"} --> group id
"D988FC9B-62FC-4ABA-9C70-E5F5821D2724:ABGroup" of application "Address Book"

As mentioned previously, the result of the make command is a reference to the newly created class. In the case above, this reference is placed into a variable named theGroup, which may be accessed later in your code.

Adding a Person to a Group

To add a person to a group in Address Book, you may use the add command. The following example code demonstrates how to add a person to a group that is referenced through the variable theGroup.

add thePerson to theGroup

Alternatively, you may choose to add a person to a group directly, rather than through the use of a variable. For example:

add thePerson to group "My Group"

Removing a Person from a Group

Removing a person from a group is just as straightforward as adding a person to a group. To remove a person from a specified group, you may use the remove command. The following example code demonstrates the proper use of this code.

remove thePerson from group "My Group"

Again, as mentioned in a tech block earlier in this article, be sure to use the save addressbook command regularly throughout your code, in order to ensure that Address Book's display is immediately updated when creating groups, adding people to groups, or removing people from groups.

Retrieving a List of Groups

There may also be times when you need to retrieve a listing of groups in Address Book. The following example code demonstrates how to retrieve a list of references to any existing groups.

groups -->
{group id "D988FC9B-62FC-4ABA-9C70-E5F5821D2724:ABGroup" of application "Address Book"}

If you prefer to retrieve only the names of the groups in Address Book, the following example code may be used.

name of every group 
--> {"My Group"}

Pulling It Together

Using the sample code and techniques that were discussed thus far throughout this article, you should now be able to start building some basic Address Book scripts, which can be expanded and integrated into a larger workflow. For example, you could develop a script that will extract contact information from a database or from an email message, and then use that content to automatically add or update contacts in your Address Book.

The example code below provides a basic demonstration of how code elements and techniques specified in this article can be pulled together to form a single script. The following example will create a new person, complete with a work email address, URL, phone number, and address.

tell application "Address Book"
   set thePerson to make new person with properties 
      {first name:"Ben", last name:"Waldie", organization:"Automated Workflows, LLC", 
      job title:"President"}
   tell thePerson
      make new email at end of emails with properties {label:"Work", 
         value:"applescriptguru@mac.com"}
      make new url at end of urls with properties 
         {label:"Work", value:"http://www.automatedworkflows.com"}
      make new phone at end of phones with properties {label:"Work", value:"610.935.0652"}
      make new address at end of addresses with properties 
         {label:"Work", street:"123 Anystreet", city:"Anytown", state:"PA", zip:"99999"}
   end tell
   make new group with properties {name:"My Group"}
   add thePerson to group "My Group"
   save addressbook
end tell

Address Book Plug-Ins

When browsing the Address Book Script Suite in Address Book's AppleScript dictionary, you may notice the action property, action title, perform action, and should enable action commands. See figure 2.


Figure 2. Address Book Plug-In Handlers

These commands are actually handlers, which may be added to a script in order to create an Address Book plug-in script. An Address Book plug-in script is a script that may be triggered from a rollover button. Rollover buttons are popup buttons, which appear when a user drags the mouse pointer over and clicks on certain labels, including phone numbers, email addresses, addresses, and more, on a person's Address Book card.

The following is example code for an Address Book plug-in. This plug-in will add a new menu item, called "Speak Phone Number" to the rollover button popup menu for each phone number of a person in Address Book. See figure 3.


Figure 3. Accessing an Address Book Plug-In Script

Whenever the "Speak Phone Number" menu item is selected, the corresponding phone number's digits will be spoken, using the say command.

The say command may be found in the User Interaction Suite of the Standard Additions scripting addition.

using terms from application "Address Book"
   on action property
      return "phone"
   end action property

   on should enable action for thePerson with theEntry
      if theEntry <> missing value then
         return true
      else
         return false
      end if
   end should enable action

   on action title for thePerson with theEntry
      return "Speak Phone Number"
   end action title

   on perform action for thePerson with theEntry
      set thePhoneNumber to value of theEntry
      repeat with a from 1 to length of thePhoneNumber
         set theCharacter to character a of thePhoneNumber
         if "0123456789" contains theCharacter then say theCharacter
      end repeat
   end perform action
end using terms from

We will now take a few moments to walk through the different handlers in the code above.

action property Handler

This handler is called when the mouse pointer first rolls over a label that serves as a rollover button, after Address Book has been launched. When triggered, the handler should return a string indicating the type of rollover button under which the script should be displayed. Options may include phone, email, address, and more.

should enable action Handler

This handler is invoked when the user actually clicks on the rollover button on a person's card. Once triggered, this handler should return a boolean value indicating whether the plug-in script may be available for the currently selected rollover. The example code above uses this opportunity to verify that the value of the phone number is not a missing value. If it is a missing value, then the menu item will not be enabled in the rollover button popup menu.

action title Handler

This handler is also triggered when the user clicks on the rollover button, but after the should enable action handler is triggered, if present. This handler should return as its result the name of the menu item that should be displayed in the rollover button popup menu.

perform action Handler

This handler is triggered when the user selects the menu item from the rollover popup menu. A reference to the selected person, as well as the selected data on which the rollover button was clicked, are passed to the handler as parameters. Add your processing code to this handler to perform the desired function.

Installing an Address Book Plug-In Script

Once you have written your Address Book plug-in script, save it as a compiled script into the Library > Address Book Plug-Ins folder at the local or user level of your hard drive. Next, re-launch the Address Book application to load the plug-in script and begin using it.

In Closing

As you are probably aware, there are other applications available for the Macintosh that provide contact management capabilities, many of which are AppleScriptable. Microsoft Entourage, Eudora, Now Up-To-Date & Contact are a few of such programs. If you are not an Address Book user, you are encouraged to explore your favorite contact management application, in order to determine whether it is scriptable. If it is scriptable, while the AppleScript terminology will be different, many of the tasks discussed in this article may still be possible to automate.

Regarding Address Book, the examples shown throughout this article should help you to begin automating some basic Address Book functions. You are encouraged to begin integrating these examples into your own custom scripts, and exploring some of the other possibilities for automating Address Book, which may not have been discussed in this article.

Until next time, keep scripting!


Ben Waldie is author of the best selling books "AppleScripting the Finder" and the "Mac OS X Technology Guide to Automator", available from http://www.spiderworks.com. Ben is also president of Automated Workflows, LLC, a firm specializing in AppleScript and workflow automation consulting. For years, Ben has developed professional AppleScript-based solutions for businesses including Adobe, Apple, NASA, PC World, and TV Guide. For more information about Ben, please visit http://www.automatedworkflows.com, or email Ben at applescriptguru@mac.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Tor Browser 12.5.5 - Anonymize Web brows...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Malwarebytes 4.21.9.5141 - Adware remova...
Malwarebytes (was AdwareMedic) helps you get your Mac experience back. Malwarebytes scans for and removes code that degrades system performance or attacks your system. Making your Mac once again your... Read more
TinkerTool 9.5 - Expanded preference set...
TinkerTool is an application that gives you access to additional preference settings Apple has built into Mac OS X. This allows to activate hidden features in the operating system and in some of the... Read more
Paragon NTFS 15.11.839 - Provides full r...
Paragon NTFS breaks down the barriers between Windows and macOS. Paragon NTFS effectively solves the communication problems between the Mac system and NTFS. Write, edit, copy, move, delete files on... Read more
Apple Safari 17 - Apple's Web brows...
Apple Safari is Apple's web browser that comes bundled with the most recent macOS. Safari is faster and more energy efficient than other browsers, so sites are more responsive and your notebook... Read more
Firefox 118.0 - Fast, safe Web browser.
Firefox offers a fast, safe Web browsing experience. Browse quickly, securely, and effortlessly. With its industry-leading features, Firefox is the choice of Web development professionals and casual... Read more
ClamXAV 3.6.1 - Virus checker based on C...
ClamXAV is a popular virus checker for OS X. Time to take control ClamXAV keeps threats at bay and puts you firmly in charge of your Mac’s security. Scan a specific file or your entire hard drive.... Read more
SuperDuper! 3.8 - Advanced disk cloning/...
SuperDuper! is an advanced, yet easy to use disk copying program. It can, of course, make a straight copy, or "clone" - useful when you want to move all your data from one machine to another, or do a... Read more
Alfred 5.1.3 - Quick launcher for apps a...
Alfred is an award-winning productivity application for OS X. Alfred saves you time when you search for files online or on your Mac. Be more productive with hotkeys, keywords, and file actions at... Read more
Sketch 98.3 - Design app for UX/UI for i...
Sketch is an innovative and fresh look at vector drawing. Its intentionally minimalist design is based upon a drawing space of unlimited size and layers, free of palettes, panels, menus, windows, and... Read more

Latest Forum Discussions

See All

Listener Emails and the iPhone 15! – The...
In this week’s episode of The TouchArcade Show we finally get to a backlog of emails that have been hanging out in our inbox for, oh, about a month or so. We love getting emails as they always lead to interesting discussion about a variety of topics... | Read more »
TouchArcade Game of the Week: ‘Cypher 00...
This doesn’t happen too often, but occasionally there will be an Apple Arcade game that I adore so much I just have to pick it as the Game of the Week. Well, here we are, and Cypher 007 is one of those games. The big key point here is that Cypher... | Read more »
SwitchArcade Round-Up: ‘EA Sports FC 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 29th, 2023. In today’s article, we’ve got a ton of news to go over. Just a lot going on today, I suppose. After that, there are quite a few new releases to look at... | Read more »
‘Storyteller’ Mobile Review – Perfect fo...
I first played Daniel Benmergui’s Storyteller (Free) through its Nintendo Switch and Steam releases. Read my original review of it here. Since then, a lot of friends who played the game enjoyed it, but thought it was overpriced given the short... | Read more »
An Interview with the Legendary Yu Suzuk...
One of the cool things about my job is that every once in a while, I get to talk to the people behind the games. It’s always a pleasure. Well, today we have a really special one for you, dear friends. Mr. Yu Suzuki of Ys Net, the force behind such... | Read more »
New ‘Marvel Snap’ Update Has Balance Adj...
As we wait for the information on the new season to drop, we shall have to content ourselves with looking at the latest update to Marvel Snap (Free). It’s just a balance update, but it makes some very big changes that combined with the arrival of... | Read more »
‘Honkai Star Rail’ Version 1.4 Update Re...
At Sony’s recently-aired presentation, HoYoverse announced the Honkai Star Rail (Free) PS5 release date. Most people speculated that the next major update would arrive alongside the PS5 release. | Read more »
‘Omniheroes’ Major Update “Tide’s Cadenc...
What secrets do the depths of the sea hold? Omniheroes is revealing the mysteries of the deep with its latest “Tide’s Cadence" update, where you can look forward to scoring a free Valkyrie and limited skin among other login rewards like the 2nd... | Read more »
Recruit yourself some run-and-gun royalt...
It is always nice to see the return of a series that has lost a bit of its global staying power, and thanks to Lilith Games' latest collaboration, Warpath will be playing host the the run-and-gun legend that is Metal Slug 3. [Read more] | Read more »
‘The Elder Scrolls: Castles’ Is Availabl...
Back when Fallout Shelter (Free) released on mobile, and eventually hit consoles and PC, I didn’t think it would lead to something similar for The Elder Scrolls, but here we are. The Elder Scrolls: Castles is a new simulation game from Bethesda... | Read more »

Price Scanner via MacPrices.net

Clearance M1 Max Mac Studio available today a...
Apple has clearance M1 Max Mac Studios available in their Certified Refurbished store for $270 off original MSRP. Each Mac Studio comes with Apple’s one-year warranty, and shipping is free: – Mac... Read more
Apple continues to offer 24-inch iMacs for up...
Apple has a full range of 24-inch M1 iMacs available today in their Certified Refurbished store. Models are available starting at only $1099 and range up to $260 off original MSRP. Each iMac is in... Read more
Final weekend for Apple’s 2023 Back to School...
This is the final weekend for Apple’s Back to School Promotion 2023. It remains active until Monday, October 2nd. Education customers receive a free $150 Apple Gift Card with the purchase of a new... Read more
Apple drops prices on refurbished 13-inch M2...
Apple has dropped prices on standard-configuration 13″ M2 MacBook Pros, Certified Refurbished, to as low as $1099 and ranging up to $230 off MSRP. These are the cheapest 13″ M2 MacBook Pros for sale... Read more
14-inch M2 Max MacBook Pro on sale for $300 o...
B&H Photo has the Space Gray 14″ 30-Core GPU M2 Max MacBook Pro in stock and on sale today for $2799 including free 1-2 day shipping. Their price is $300 off Apple’s MSRP, and it’s the lowest... Read more
Apple is now selling Certified Refurbished M2...
Apple has added a full line of standard-configuration M2 Max and M2 Ultra Mac Studios available in their Certified Refurbished section starting at only $1699 and ranging up to $600 off MSRP. Each Mac... Read more
New sale: 13-inch M2 MacBook Airs starting at...
B&H Photo has 13″ MacBook Airs with M2 CPUs in stock today and on sale for $200 off Apple’s MSRP with prices available starting at only $899. Free 1-2 day delivery is available to most US... Read more
Apple has all 15-inch M2 MacBook Airs in stoc...
Apple has Certified Refurbished 15″ M2 MacBook Airs in stock today starting at only $1099 and ranging up to $230 off MSRP. These are the cheapest M2-powered 15″ MacBook Airs for sale today at Apple.... Read more
In stock: Clearance M1 Ultra Mac Studios for...
Apple has clearance M1 Ultra Mac Studios available in their Certified Refurbished store for $540 off original MSRP. Each Mac Studio comes with Apple’s one-year warranty, and shipping is free: – Mac... Read more
Back on sale: Apple’s M2 Mac minis for $100 o...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $100 –... Read more

Jobs Board

Licensed Dental Hygienist - *Apple* River -...
Park Dental Apple River in Somerset, WI is seeking a compassionate, professional Dental Hygienist to join our team-oriented practice. COMPETITIVE PAY AND SIGN-ON Read more
Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Sep 30, 2023 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
*Apple* / Mac Administrator - JAMF - Amentum...
Amentum is seeking an ** Apple / Mac Administrator - JAMF** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Child Care Teacher - Glenda Drive/ *Apple* V...
Child Care Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.