Applescript to add sender of message to specific group in Contacts I'm trying to set up an Applescript to add the sender of a selected message in Apple Mail to a specific group in the Contacts app. By reconfiguring the code provided in this answer, I worked up the following but it isn't working. Any suggestions on what I am doing wrong?

    tell application "Mail"
    set theMessage to selection
    tell application "Contacts"
        set theGroup to "_TEST"
    end tell
    set theSender to sender of theMessage
    tell application "Contacts"
        set theName to name of theSender
        set thePerson to make new person with properties {first name:name of theSender}
        add thePerson to theGroup
    end tell
    tell application "Contacts" to save
    end tell
Try this, it will create a contact with proper first name, last name and email address:

tell application "Mail"
set theMessages to selection
if theMessages is not {} then -- check empty list
    set theSenderName to extract name from sender of item 1 of theMessages
    set nameArray to my split(theSenderName, " ")
    set theFirstName to item 1 of nameArray
    set theLastName to last item of nameArray
    set theEmail to extract address from sender of item 1 of theMessages

    tell application "Contacts"
        set theGroup to group "_TEST"
        set thePerson to make new person with properties {first name:theFirstName, last name:theLastName}
        make new email at end of emails of thePerson with properties {label:"Work", value:theEmail}
        add thePerson to theGroup
        save
    end tell
    end if
end tell

on split(theString, theDelimiter)
    set oldDelimiters to AppleScript's text item delimiters
    set AppleScript's text item delimiters to theDelimiter
    set theArray to every text item of theString
    set AppleScript's text item delimiters to oldDelimiters
    return theArray
end split


There were a few issues with your original attempt, here's how I worked around them.


For starters, selection gives you a list of items (even if it's just a list of one), so you need to pick the first element from the selection.
In mail, sender gives you a not very useful string with the name and email combined. extract name from and extract address from give you useful strings.
The name string is the full name, but Contacts.app expects separate first and last names, so I split that string (using a handy function found here) to make a decent guess at first and last names. This may give unexpected results from strangely formatted names in emails.


If you have any problems with this one, let me know and I'll see if I can fix them. In the future, it may be helpful to run the scripts in AppleScript Editor, and check the Event Log for details on what's failing (error messages are useful, if only to put into Google or give others a starting point for solving your problem).