2
votes

I have just started to learn Google Apps Script to solve one practical task. I'd like to write a script that periodically exports all contacts in my Google account into a CSV file and sends it to a predefined email address. This should be a kind of automatic versioned backup if data loss will occur in my contact list.

Actually what I am trying to do is to use the native export functionality available in the web interface of the Google contacts (More > Export) in my script. I skimmed through the Google API, but I could not find a service or object in the Google API that does what I need. Is it possible at all?

1
Looks to me like everything you will need is right here I think you will have to make the csv list and save it in a file yourself. But my guess is that it's fairly simple things to do.Cooper
You can probably get what you need at Gmail Contacts the old version. Click the MORE and you'll see the export. I think this is the link.Cooper
@Cooper, did you understand me? I need to do this programmatically from a GAS script.TecMan
I don't think I did but I do nowCooper

1 Answers

1
votes

Here's something I threw together to get a few of the basic fields in your contacts into something that could be a csv output. You may want to add more fields and perhaps use different delimiters.

function getAllContacts() {
  var contactsA=ContactsApp.getContacts();
  var s='';
  var br='<br />';//line delimiter change to linefeed when not using html dialog
  var dlm=' ~~~ ';//field delimiter
  for(var i=0;i<contactsA.length;i++)
  {

    s+=Utilities.formatString('<br />\'%s\',\'%s\',\'%s\',\'%s\',\'%s\'%s',
    (typeof(contactsA[i].getFullName())!='undefined')?contactsA[i].getFullName():'',
    (typeof(contactsA[i].getAddresses().map(function (v,i,A) { return A[i].getAddress();}))!='undefined')?contactsA[i].getAddresses().map(function (v,i,A) { return A[i].getAddress();}).join(dlm):'',
    (typeof(contactsA[i].getEmails().map(function(v,i,A) {return A[i].getAddress();}))!='undefined')?contactsA[i].getEmails().map(function(cV,i,A) {return A[i].getAddress();}).join(dlm):'',
    (typeof(contactsA[i].getPhones().map(function(v,i,A){return A[i].getPhoneNumber();}))!='undefined')?contactsA[i].getPhones().map(function(v,i,A){return A[i].getPhoneNumber();}).join(dlm):'',
    (typeof(contactsA[i].getCompanies().map(function(v,i,A){return A[i].getCompanyName();}))!='undefined')?contactsA[i].getCompanies().map(function(v,i,A){return A[i].getCompanyName();}).join(dlm):'',br);
  }
  var ui=HtmlService.createHtmlOutput(s).setWidth(800)  ;
  SpreadsheetApp.getUi().showModelessDialog(ui, 'Contacts')
}