Ben Spear
Ben Spear

Reputation: 51

automatically export Google Contacts data to Google Sheets

I want to automatically fetch contact info from my Google Contacts and display it in a Google Sheets spreadsheet.

I have used the following code for fetching and displaying fullName

`function getName() { // Gets the names of everyone in the 'GUIDES' label in Google Contacts
  var group = ContactsApp.getContactGroup('GUIDES');
  var contacts = group.getContacts(), output = [];  
  for(var i = 0, iLen = contacts.length; i < iLen; i++) {
    var fullname = contacts[i].getFullName();    
    if(fullname) {
      output.push([fullname]);
    } else {
      continue;
    }
  }
  SpreadsheetApp.getActiveSheet().getRange(4, 3, output.length, 1).setValues(output);
}`

This works correctly and returns all names in the group labelled "Guides"

I also want to return email addresses. When I use the same code with .getEmails instead of .getFullName it returns the email field but not the string I want.

I have tried .getEmails(ContactsApp.Field.HOME_EMAIL); with .getAddress() as below but it doesn't work. I get the Error

Cannot find function getAddress in object EmailField.

`function getAddress(){
 var group = ContactsApp.getContactGroup('GUIDES');
 var contact = group.getContacts(),output = [];  
  for(var i = 0, iLen = contact.length; i < iLen; i++) {
 var addresses = contact[i].getEmails(ContactsApp.Field.HOME_EMAIL);
    if(addresses) {
      output.push([addresses.getAddress()]);
     } else {
      continue;
    }
  }
  SpreadsheetApp.getActiveSheet().getRange(4, 4, output.length, 1).setValues(output);
}
   `

I would like the email address for the field to be displayed, not the field itself.

Upvotes: 2

Views: 1241

Answers (1)

Tanaike
Tanaike

Reputation: 201703

The values retrieved by getEmails() is an array. So how about this modification?

Modified script:

When your script is modified, please modify as follows.

From:
output.push([addresses.getAddress()]);
To:
output.push([addresses.map(function(e) {return e.getAddress()}).join(",")]);

Note:

  • If empty values are retrieved from the modified script, please also try to modify as follows.

    • From:

      var addresses = contact[i].getEmails(ContactsApp.Field.HOME_EMAIL);
      
    • To:

      var addresses = contact[i].getEmails();
      

References:

If I misunderstood your question and this was not the result you want, I apologize.

Upvotes: 2

Related Questions