by
3
7
5,878
1
Top 1% !
Famous
Pearl of Wisdom
Easy-to-find
Refined
Tuned
OpenSource
Popularity: 1189th place

Published on:

.NETFramework4.0
ClassNameGmailHelper
InputName0token
InputType0string
Languagecsharp
LicenseMIT_X11
MethodNameGetContacts
MethodNameGetRedirUriForContacts
OSWindows
OutputTypeList<SimpleContact>
OutputTypestring
RequiredLibfastJSON
RequiredLibGoogle.GData.Client
RequiredLibGoogle.GData.Contacts
RequiredLibGoogle.GData.Extensions

How to retrieve GMail contacts via API, using OAuth2 token and not username/password credentials

This class takes charge of the interaction with Google Contacts API, authenticating with an AccessToken authorization flow. In this way the final user should type the credentials in the Google form and not in your form.
The "token" parameter of GetContacts() method is the one sent by Google to the callback url specified  in the static constant "s_redirUri" (that should match the value added in the Settings of your App on Google API dashboard).
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/235509/How-to-retrieve-GMail-contacts-via-API--?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
using System; using System.Linq; using System.Collections.Generic; using Google.Contacts; using Google.GData.Contacts; using Google.GData.Client; using Google.GData.Extensions; namespace Contact.Utils { /// <summary> /// Summary description for GmailHelper /// </summary> public class GmailHelper { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static fastJSON.JSON jsonUtils = EntityUtils.InitJSONUtils(); private static readonly string APP_NAME = "my app name"; private static readonly string s_ClientId = "client id given by Google"; private static readonly string s_ClientSecret = "secret given by Google; private static readonly string s_accessTokenUrl = "https://accounts.google.com/o/oauth2/token"; private static readonly string s_redirUri = WebConfig.Current.PublicPath + "User/GmailCallback"; #region PUBLIC API ////////////////////////////////////////////////////////////////////////////////////////////////////// public static string GetRedirUriForContacts() { return string.Format("https://accounts.google.com/o/oauth2/auth?scope=https://www.google.com/m8/feeds&redirect_uri={0}&response_type=code&client_id={1}", s_redirUri, s_ClientId); } public static List<SimpleContact> GetContacts(string token) { List<SimpleContact> results = new List<SimpleContact>(); //exchange the code for a token: string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", token, s_ClientId, s_ClientSecret, s_redirUri); string accessTokenResp = Utilities.SendHttpRequest(s_accessTokenUrl, postData, true); if (string.IsNullOrEmpty(accessTokenResp)) return results; AccessTokenStruct parsedJson = null; try { parsedJson = jsonUtils.ToObject<AccessTokenStruct>(accessTokenResp); } catch (Exception e) { log.ErrorFormat("Cannot deserialize access token response: '{0}' due to {1}", accessTokenResp, e.Message); return results; } if (parsedJson == null) return results; //ask for contacts: RequestSettings settings = new RequestSettings(APP_NAME, parsedJson.access_token); settings.AutoPaging = true; ContactsRequest cr = new ContactsRequest(settings); Feed<Contact> contactsFeed = cr.GetContacts(); IEnumerable<Contact> contacts = null; if (contactsFeed != null) contacts = contactsFeed.Entries; if (contacts == null) return results; try { foreach (SimpleContact c in contacts) { if (c.PrimaryEmail == null) continue; string preferredEmail = c.PrimaryEmail.Address; if (string.IsNullOrEmpty(preferredEmail)) continue; string[] otherEmails = null; if (c.Emails != null) otherEmails = c.Emails.Select(e => e.Address).ToArray(); S2CContact contact = new S2CContact((c.Name == null ? "" : c.Name.FullName), preferredEmail, otherEmails); results.Add(contact); } } catch (Exception e) { log.ErrorFormat("Cannot retrieve contacts due to {0}", e.Message); return results; } return results; } #endregion ////////////////////////////////////////////////////////////////////////////////////////////////////// } public class AccessTokenStruct { public string access_token { get; set; } public int expires_in { get; set; } public string token_type { get; set; } public AccessTokenStruct() { } } public class SimpleContact { public string PreferredEmail { get; set; } public string Name { get; set; } public string[] Emails { get; set; } public SimpleContact(string name, string preferredEmail, string[] emails = null) { Name = name; PreferredEmail = preferredEmail; if (emails == null) Emails = new string[] { preferredEmail }; else { List<string> allEmails = new List<string>(emails); allEmails.Add(preferredEmail); Emails = allEmails.Distinct().ToArray(); } } public override string ToString() { if (string.IsNullOrEmpty(Name)) return PreferredEmail; else return string.Format("{0} [{1}]", Name, PreferredEmail); } } }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus