1

I'm trying to create a contact using Javascript for Automation (JXA) but I haven't been able to figure out how to add an email address to the contact.

This is the code for adding the contact:

Contacts = Application('Contacts')
person = Contacts.Person().make()
person.firstName = "Tom"
person.lastName = "Tester"
Contacts.save()

That works as expected, i. e. it creates a contact with a first and last name.

I then tried to add this code to add an email address to the contact:

Contacts = Application('Contacts')
person = Contacts.Person().make()
person.firstName = "Tom"
person.lastName = "Tester"
email = Contacts.Email().make()
email.label = "Work"
email.value = "mail@test.de"
Contacts.add({ email, to: person })
Contacts.save()

The line email = Contacts.Email().make() gives the error "Can't make or move that element into that container."

I also tried email = Contacts.ContactInfo().make(), same error. Then I tried email = Contacts.Email(), which works, including assigning the two properties label and value thereafter, but then the line Contacts.add({ email, to: person }) fails with the error "Can't convert types."

I'm pretty much stumped as to how this is supposed to work. None of the (very few) JXA code examples I could find were of any help in this particular case. I assume I'm getting some fundamental aspect of how this API is supposed to work wrong, but I just can't figure it out and the little documentation that's available hasn't helped either. Anybody have a clue how this is supposed to work?

Tom Borowski
  • 683
  • 1
  • 5
  • 7

1 Answers1

1

Found the answer through trial and error, no thanks to Apple's documentation:

Contacts = Application('Contacts')
person = Contacts.Person().make()
person.firstName = "Tom"
person.lastName = "Tester"
email = Contacts.Email({ label: "Work", value: "mail@test.de" })
person.emails.push(email)
Contacts.save()

So I guess the "trick" is to create an object of the Email class while not using make(). Why you have to use make() when creating the Person and not when creating anything else is beyond me.

Tom Borowski
  • 683
  • 1
  • 5
  • 7
  • 1
    JXA is badly designed, crippled, and abandoned by Apple. You're much better off using AppleScript for application automation tasks—lousy language, but at least it does Apple events right and has a user community to help you when you get stuck. It's pretty easy to [call AppleScript handlers from other languages](http://appscript.sourceforge.net/asoc.html) via the AppleScript-ObjC bridge, so you can still mix-and-match with `$language` of your choice. – foo Dec 09 '18 at 11:15