Applescript to find and add specific contacts to a group

applescriptcontacts

I tried to re-jig the applescript from these two answers, but no dice. It seems to work if you're creating contacts at the same time, but not when finding existing contacts.

tell application "Contacts"
    set thePersons to {"john@email.com"} as list
    set theGroup to group "MyGroup"
    repeat with thePerson in thePersons
        delay 0.1
        set theContact to (first person whose value of last email contains thePerson)
        add theContact to theGroup
    end repeat
end tell

The above runs without error, but nothing happens, no one is added. I'm not exactly sure what I'm doing wrong.

The goal is to produce an applescript where I can just provide a list of emails and it'll find/add them to a specified group.

Best Answer

This is one way to do get the syntax right for this task:

to addContactsByEmail:(e_mails as list) toNamedGroup:(group_name as text)
        local e_mails, group_name
        tell application id "com.apple.AddressBook"
                set target_group to the group named group_name
                repeat with e_mail in the e_mails
                        tell (the first person whose e_mail is in the ¬
                               value of its emails) to if exists then ¬
                               add it to the target_group
                end repeat
                save
        end tell
end addContactsByEmail:toNamedGroup:

I've also wrapped it in a handler to be called as a re-usable code block, e.g.

my addContactsByEmail:{"foo@bar.com", "people@desks.com"} toNamedGroup:"Imaginary Friends"

You may wish to add some error-handling to cover the situations where the specified named group doesn't exist. Currently, it'll throw an error (the same as yours would), but you could either elect to exist the handler gracefully if the group doesn't exist; or to create the group automatically.