کد:
//First, a small class to hold the data
/// <summary>
/// class to hold the data from our Google contacts
/// </summary>
public class GoogleContacts
{
public string title { get; set; }
public string email { get; set; }
public string im { get; set; }
}
//Next method for retrieving the contacts
/// <summary>
/// method for retrieving all contacts in a persons Google Mail address book
/// </summary>
/// <param name="appName">the application making the request</param>
/// <param name="un">username of the account</param>
/// <param name="pwd">password of the account</param>
/// <returns></returns>
public static List<GoogleContacts> GetGoogleContacts(string appName, string un, string pwd)
{
//list to hold all contacts returned
List<GoogleContacts> contactList = new List<GoogleContacts>();
//create an instance of the request settings
RequestSettings settings = new RequestSettings(appName, un, pwd);
//set AutoPaging to true so we get all the contacts
settings.AutoPaging = true;
//now send ouor request for contacts
ContactsRequest request = new ContactsRequest(settings);
//retrieve the contacts returned
Feed<Contact> feed = request.GetContacts();
//here we will loop through all the contacts returned and add them to our list
foreach (Contact contact in feed.Entries)
{
GoogleContacts c = new GoogleContacts();
c.title = string.IsNullOrEmpty(contact.Title) ? "Name Not Present" : contact.Title;
c.email = contact.Emails[0].Address;
c.im = contact.IMs.Count == 0 ? "IM Address Not Present" : contact.IMs[0].Address;
contactList.Add(c);
}
return contactList;
}
//Sample usage
static void Main(string[] args)
{
List<GoogleContacts> list = GetGoogleContacts("GoogleTest", "YourGmailAddress", "YourGmailPassword");
Console.WriteLine("Total Contacts Retrieved: " + list.Count());
Console.WriteLine("************************************************");
Console.WriteLine();
foreach (GoogleContacts contact in list)
{
Console.WriteLine(contact.title);
Console.WriteLine(contact.email);
Console.WriteLine(contact.im);
Console.WriteLine();
}
Console.ReadLine();
}