P
P
pnic2016-08-02 19:01:53
gmail
pnic, 2016-08-02 19:01:53

How to create Gmail contacts with a script?

I want to import contacts by server script from different sources to a specific mailbox.
With the help of google api, it was possible to create an access key, create contacts, get a list, but they are not visible directly through the gmail web interface

#!/usr/bin/python
# -*- coding: utf-8 

import httplib2
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client import tools
import json

from apiclient.discovery import build

import gdata.data
import gdata.gauth
import gdata.contacts.client
import gdata.contacts.data

import httplib2 

from oauth2client.service_account import ServiceAccountCredentials

credentials = ServiceAccountCredentials.from_json_keyfile_name('key.json', scopes='https://www.google.com/m8/feeds/')

# http://stackoverflow.com/questions/16026286/using-oauth2-with-service-account-on-gdata-in-python
gd_client = gdata.contacts.client.ContactsClient(source='My Project')
auth2token = gdata.gauth.OAuth2TokenFromCredentials(credentials)
gd_client = auth2token.authorize(gd_client)

def CreateContact(gd_client, phone):
    new_contact = gdata.contacts.data.ContactEntry(
      name=gdata.data.Name(full_name=gdata.data.FullName(text='test'))
    )
    new_contact.phone_number.append(gdata.data.PhoneNumber(text=phone, rel=gdata.data.WORK_REL, primary='true'))
    contact_entry = gd_client.CreateContact(new_contact)
    print "Contact's ID: %s" % contact_entry.id.text

CreateContact(gd_client, '9999')

def PrintAllContacts(gd_client):
  feed = gd_client.GetContacts()
  #print feed.entry.phone
  for i, entry in enumerate(feed.entry):
    print '\n%s %s' % (i+1, entry.name)
    if entry.content:
      print '    %s' % (entry.content.text)
    # Display the primary email address for the contact.
    for email in entry.email:
      if email.primary and email.primary == 'true':
        print '    %s' % (email.address)
    for phone_number in entry.phone_number:
      if phone_number.primary and phone_number.primary == 'true':
        print '    %s' % (phone_number.text)
    # Show the contact groups that this contact is a member of.
    for group in entry.group_membership_info:
      print '    Member of group: %s' % (group.href)
    # Display extended properties.
    for extended_property in entry.extended_property:
      if extended_property.value:
        value = extended_property.value
      else:
        value = extended_property.GetXmlBlob()
      print '    Extended Property - %s: %s' % (extended_property.name, value)

print PrintAllContacts(gd_client)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question