Wednesday, November 26, 2014

How to Access Email OR Contacts from Gmail or Google using Asp.net.

How to Access Email OR Contacts from Gmail or Google using Asp.net.

Hi, I was trying to get email list of a particular user from gmail using Oauth to invite friends in my recent project.

Now Question is How to Access Email or Contacts from Gmail or Google. So,we will access email or contacts from google contacts in ASP.NET page.

 So implementation of Google Contact Api with oauth read following steps.

First we have to create an account with google. Then, access the google developer console.https://console.developers.google.com/project (click here to access google developer console)
Create a project

Note: We will Access email list using OAuth of google. For more information on this topic you can click on the following link: https://developers.google.com/google-apps/contacts/v3/



Enable the Contact API

Browse Contact API in Browse API text box and change status as ON.


Create New client ID

Click on APIs & auth in left side tab, then click on Credentials menu and create new client ID.



Now our setup is ready for use API.

Now we have to hit an http request to authenticate the google user and get permission to access contact list.

Following code will hit the request to authenticate user for getting permission to access the contact list.


string AppClientID="xxxxxxxxxxx.apps.googleusercontent.com";
string AppRedirectURL="http://localhost:50485/Default.aspx";
Response.Redirect("https://accounts.google.com/o/oauth2/auth?" +"client_id=" + AppClientID + "&" +"redirect_uri=" + HttpUtility.UrlEncode(AppRedirectURL) + "&" +"scope=" + HttpUtility.UrlEncode("https://www.googleapis.com/auth/contacts.readonly") + "&" +"response_type=code");

After authenticating the user, google api redirect to a particular page, that we had already setup.

(string AppRedirectURL="http://localhost:50485/Default.aspx";)

And when it will redirect, you will get an authentication code within a query string with parameter name code.  We have to handle that response.

after we receive the code we will hit another request and along with this request we will include the received code. If the code matches, we will get an access token. 

string AppClientID="xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";//put your app id
string AppClientSecret = "xxxxxxxxxxxxxxxx";//put your app secret
string AppRedirectURL = "http://localhost:50485/Default.aspx";
if (Request.QueryString["code"] != null && Request.QueryString["error"] != "access_denied")
{
WebRequest requestLogIn = null;
Stream stream = null;
WebResponse response = null;
StreamReader reader = null;

string sendData = "code=" + Request.QueryString["code"] + "&";
       sendData += "client_id=" + AppClientID + "&";
       sendData += "client_secret=" + AppClientSecret + "&";
       sendData += "redirect_uri=" + AppRedirectURL + "&";
       sendData += "grant_type=authorization_code";            
       requestLogIn= WebRequest.Create("https://accounts.google.com/o/oauth2/token");
       requestLogIn.Method = "POST";
       requestLogIn.ContentType = "application/x-www-form-urlencoded";

       byte[] arrayToSend = Encoding.UTF8.GetBytes(sendData);
       requestLogIn.ContentLength = arrayToSend.Length;

       stream = requestLogIn.GetRequestStream();
       stream.Write(arrayToSend, 0, arrayToSend.Length);
       stream.Close();
       response = requestLogIn.GetResponse();

     if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
                {
                    stream = response.GetResponseStream();
                    reader = new StreamReader(stream);
                    responseValue = reader.ReadToEnd();
                    reader.Close();
varlJSONResponse = new JavaScriptSerializer().Deserialize<JSONResponseToken>(responseValue);
                }
 }

For Deserialize the response value we have to create a class following.

 class JSONResponseToken
    {
        public string Access_Token { get; set; }
    }

Now we will hit api request for google email. and in its header we will pass the access_Token and in return we will receive the emails list. 

WebRequest myRequest = WebRequest.Create("https://www.google.com/m8/feeds/contacts/default/full?max-results=1000");
myRequest.Method = "GET";
myRequest.Headers.Add("Authorization", "Bearer " + lJSONResponse.Access_Token);
response = myRequest.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
                    {
                        stream = response.GetResponseStream();
                        reader = new StreamReader(stream);
                        responseValue = reader.ReadToEnd();
                    }

Now finally we get the response in a particular format that we had setup in our api request.(by default its xml)
Now it’s done. We have to parse that response and print or use the emails.

after implementation of code output will be look like follow.



I hope its help you, if have need any kind of help then you can email or comments.
You can also download zip file of .net solution from following link
Download Source Code





No comments:

Post a Comment