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

delete email field google apps script


I am simply trying to use google apps script code to create a new contact, and label the email field as "Work" because it defaults to "Home" when it is created. (I am trying to do this using a form, but for test purposes, it's a simple Run trigger)

I have tried so many different iterations that there are too many to list here. But my latest workaround (as all things are with google) is to let the thing create the default "Home" email field when the contact is created, then add a "Work" field email, and then delete the "Home" - but the deleteEmailField which is listed in the google documentation never works.

Here is the latest I've put together:

function testAddcontact() {
var firstName= "Contact"
var lastName= "Test2"
var email= "[email protected]"
var newcontact = ContactsApp.createContact( firstName, lastName , email );
newcontact.addEmail("Work", email);
newcontact.deleteEmailField("Home");
}

I have tried so many variations that I can't provide all the code I've worked on here, but I have inserted above my latest attempt.

Thoughts anyone on how to create a contact and label that email address "Work" instead of the default "Home"?


Solution

  • This snippet should work:

    function testAddcontact() {
      var firstName= "Contact"
      var lastName= "Test2"
      var email= "[email protected]"
      var newcontact = ContactsApp.createContact( firstName, lastName , email );
      newcontact.addEmail(ContactsApp.Field.WORK_EMAIL, email);
      var emailArr = newcontact.getEmails(ContactsApp.Field.HOME_EMAIL);
      emailArr[0].deleteEmailField();
    }
    

    just remember that:

    standard labels are Field objects

    deleteEmailField is a EmailField method