Get Google contacts with OAuth 2.0

Although neither POP3 nor IMAP protocol allows retrieving the list of user’s contacts, it is possible to use Google API for that.

As long as you are using one of OAuth 2.0 scenarios:

Mail.dll email component allows you to easy download Gmail contacts of a particular user.

Turn on Contacts API

Remember to turn on “Contacts API” in Google management console.

Remember to add request for calendar data access using GoogleScope.ContactsScope.

// C#

List<GoogleScope> scope = new List<GoogleScope>
    {
        GoogleScope.ImapAndSmtp.Name,
        GoogleScope.EmailScope,
        GoogleScope.ContactsScope
    };
' VB.NET

Dim scope As New List(Of GoogleScope)() { _
    GoogleScope.ImapAndSmtp.Name, _
    GoogleScope.EmailScope, _
    GoogleScope.ContactsScope _
}

// C#

GoogleApi api = new GoogleApi(accessToken);

XmlDocument contacts = api.GetContacts();

XmlNamespaceManager nsmgr = new XmlNamespaceManager(contacts.NameTable);
nsmgr.AddNamespace("gd", "http://schemas.google.com/g/2005");
nsmgr.AddNamespace("a", "http://www.w3.org/2005/Atom");

foreach (XmlNode contact in contacts.GetElementsByTagName("entry"))
{
    XmlNode title = contact.SelectSingleNode("a:title", nsmgr);
    XmlNode email = contact.SelectSingleNode("gd:email", nsmgr);

    Console.WriteLine("{0}: {1}", 
        title.InnerText, 
        email.Attributes["address"].Value);
}
' VB.NET

Dim api As New GoogleApi(accessToken)

Dim contacts As XmlDocument = api.GetContacts()

Dim nsmgr As New XmlNamespaceManager(contacts.NameTable)
nsmgr.AddNamespace("gd", "http://schemas.google.com/g/2005")
nsmgr.AddNamespace("a", "http://www.w3.org/2005/Atom")

For Each contact As XmlNode In contacts.GetElementsByTagName("entry")
	Dim title As XmlNode = contact.SelectSingleNode("a:title", nsmgr)
	Dim email As XmlNode = contact.SelectSingleNode("gd:email", nsmgr)
	Console.WriteLine("{0}: {1}", _
            title.InnerText, _
            email.Attributes("address").Value)
Next

Tags: , ,

4 Responses to “Get Google contacts with OAuth 2.0”

  1. Ruddy Says:

    Great code! just I needed, but I get 401 error response code, when I reach the line:

    XmlDocument contacts = api.GetContacts();

    I am sure I got the accessToken correct, & can read Imap.

    Ant idea what happen?

  2. Ruddy Says:

    It’s done.
    I got it wrong with the SCOPE, after after correct it every thing go right.

    Thanks! great code.

  3. Subham Says:

    I get 401 error response code, when I reach the line:

    XmlDocument contacts = api.GetContacts();

    I am 100% sure I got the accessToken correct, & can read Imap.

    help me to solve this issue ASAP.

  4. Limilabs support Says:

    @Subham,

    If you are getting 401 error (Unauthorized), it means that you haven’t got correct access token.
    Have you specified calendar scope (GoogleScope.ContactsScope)?

Questions?

Consider using our Q&A forum for asking any questions.