Search code examples
google-apps-scriptgoogle-contacts-api

Unable to add an address to a Contact via Google Apps Script


I can create a Contact via Google Apps Script, and add a phone number but I've been unable to add an address, getting an error "The resource you requested could not be located."

Note: fName, actualLastName, email, address & phone1 are all strings

//  create the Contact
var newContact = ContactsApp.createContact(fName, actualLastName, email);
var newName = newContact.getFullName();
Logger.log("newName: " + newName);
Logger.log("New contact added");



//  attempt to add the address - DOESN'T WORK
try {
  Logger.log("Wanting to add this address: ", address);
  newContact.addAddress(ContactsApp.Field.WORK_ADDRESS, address);  
  Logger.log("Address added");
} catch(err) {
  Logger.log("Stumbled while trying to add address: " + err.message);
  Browser.msgBox("Stumbled while trying to add address to contact");
}

The logged error message is: "Info Stumbled while trying to add address: The resource you requested could not be located."

Adding a phone number works fine:

newContact.addPhone(ContactsApp.Field.MOBILE_PHONE, phone1);

And the Contact gets added to the appropriate Group:

var group = ContactsApp.getContactGroup("System Group: My Contacts");
group.addContact(newContact);

Solution

  • As one workaround, I would like to propose the following modification. In this modification, the contact ID is retrieved when the contact is created. And, addPhone and addAddress are used for the contact object retrieving with the contact ID.

    Modified script:

    var newContact = ContactsApp.createContact(fName, actualLastName, email);
    var contactId = newContact.getId();
    var c = ContactsApp.getContactById(contactId);
    c.addAddress(ContactsApp.Field.WORK_ADDRESS, address);
    

    Reference: