ASP.NET - How to Get Yahoo mail contact in your website

Asked By sonu Ranjan on 01-Dec-12 12:43 AM
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;


/// <summary>
/// Summary description for YahooContact
/// </summary>
public class YahooContact
{
public YahooContact()
{
    }


    private const string _addressBookUrl = "http://address.yahoo.com/yab/us/Yahoo_ab.csv?loc=us&.rand=1671497644&A=H&Yahoo_ab.csv";
    private const string _authUrl = "https://login.yahoo.com/config/login?";
    private const string _loginPage = "https://login.yahoo.com/config/login";
    private const string _userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";


    public bool ExtractMail( string userName,string Password)
    {
        bool Result = false;
        MailContactList list = new MailContactList();


        try
        {
            WebClient _webClient = new WebClient();
            _webClient.Headers[HttpRequestHeader.UserAgent] = _userAgent;
            _webClient.Encoding = Encoding.UTF8;
            byte[] firstResponse = _webClient.DownloadData(_loginPage);
            string firstRes = Encoding.UTF8.GetString(firstResponse);
            NameValueCollection postToLogin = new NameValueCollection();
            Regex regex = new Regex("type=\"hidden\" name=\"(.*?)\" value=\"(.*?)\"", RegexOptions.IgnoreCase);
            Match match = regex.Match(firstRes);
            while (match.Success)
            {
                if (match.Groups[0].Value.Length > 0)
                {
                    postToLogin.Add(match.Groups[1].Value, match.Groups[2].Value);
                }
                match = regex.Match(firstRes, match.Index + match.Length);
            }
            
            postToLogin.Add("login", userName);
            postToLogin.Add(".save", "Sign In");
            postToLogin.Add(".persistent", "y");
            postToLogin.Add("passwd",Password); 
            //string login = _netCredental.UserName.Split('@')[0];
           // postToLogin.Add("login", login);
            //postToLogin.Add("passwd", _netCredental.Password);
            _webClient.Headers[HttpRequestHeader.UserAgent] = _userAgent;
            _webClient.Headers[HttpRequestHeader.Referer] = _loginPage;
            _webClient.Encoding = Encoding.UTF8;
            _webClient.Headers[HttpRequestHeader.Cookie] = _webClient.ResponseHeaders[HttpResponseHeader.SetCookie];
            _webClient.UploadValues(_authUrl, postToLogin);
            string cookie = _webClient.ResponseHeaders[HttpResponseHeader.SetCookie];
            if (string.IsNullOrEmpty(cookie))
            {
                return false;
            }


            string newCookie = string.Empty;
            string[] tmp1 = cookie.Split(',');
            foreach (string var in tmp1)
            {
                string[] tmp2 = var.Split(';');
                newCookie = String.IsNullOrEmpty(newCookie) ? tmp2[0] : newCookie + ";" + tmp2[0];
            }


            // set login cookie  
            _webClient.Headers[HttpRequestHeader.Cookie] = newCookie;
            byte[] thirdResponse = _webClient.DownloadData(_addressBookUrl);
            string thirdRes = Encoding.UTF8.GetString(thirdResponse);
            string crumb = string.Empty;
            Regex regexCrumb = new Regex("type=\"hidden\" name=\"\\.crumb\" id=\"crumb1\" value=\"(.*?)\"", RegexOptions.IgnoreCase);
            match = regexCrumb.Match(thirdRes);
            if (match.Success && match.Groups[0].Value.Length > 0)
            {
                crumb = match.Groups[1].Value;
            }


            NameValueCollection postDataAB = new NameValueCollection();
            postDataAB.Add(".crumb", crumb);
            postDataAB.Add("vcp", "import_export");
            postDataAB.Add("submit[action_export_yahoo]", "Export Now");
            _webClient.Headers[HttpRequestHeader.UserAgent] = _userAgent;
            _webClient.Headers[HttpRequestHeader.Referer] = _addressBookUrl;
            byte[] FourResponse = _webClient.UploadValues(_addressBookUrl, postDataAB);
            string csvData = Encoding.UTF8.GetString(FourResponse);
            string[] lines = csvData.Split('\n');
            foreach (string line in lines)
            {
                string[] items = line.Split(',');


                if (items.Length < 5)
                {
                    continue;
                }


                string email = items[4];
                string name = items[3];
                if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(name))
                {
                    email = email.Trim('\"');
                    name = name.Trim('\"');
                    if (!email.Equals("Email") && !name.Equals("Nickname"))
                    {
                        MailContact mailContact = new MailContact();                        
                        mailContact.Name = name;
                        mailContact.Email = email;
                        list.Add(mailContact);
                    }
                }
            }


            Result = true;
        }
        catch
        { 
          
        }
        return Result;
        
    }




    public class MailContact
    {
        private string _email = string.Empty;
        private string _name = string.Empty;


        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }


        public string Email
        {
            get { return _email; }
            set { _email = value; }
        }


        public string FullEmail
        {
            get { return Email; }
        }
    }


    public class MailContactList : List<MailContact>
    {
    }
}


I m using this code to Retrieve yahoo Mail contact. But i have not Get Good Response of this coed..so Any Idea and Views of Viewers to share this Regarding Post..  


Lalit M replied to sonu Ranjan on 01-Dec-12 02:47 AM

Hi…

You can try this code sample

HTML Code

-------

    <form id="form1" runat="server">

        <b>Fetch Contacts From yahoo using asp.net and c#</b>


        Yahoo Login


        <table>

          <tr>

            <td>

              UserName:

            </td>

            <td>

              <asp:TextBox ID="txtusername" runat="server"></asp:TextBox>e.g user@yahoo.com

            </td>

          </tr>

          <tr>

            <td>

              Password:

            </td>

            <td>

              <asp:TextBox ID="txtpassword" runat="server" TextMode="Password"></asp:TextBox>

            </td>

          </tr>

          <tr>

            <td colspan="2">

              <asp:Button ID="btnSubmit" runat="server" Text="Get Contacts From Yahoo Account"

                OnClick="btnSubmit_Click" />

            </td>

          </tr>

        </table>

        <div id="dvcontacts" runat="server">

        </div>

      </form>


CS Code Sample

--------


using System;

using System.Collections.Specialized;

using System.Net;

using System.Text;

using System.Text.RegularExpressions;

using System.Collections;


public partial class YahooContact : System.Web.UI.Page

{

   private const string _addressBookUrl = "http://address.yahoo.com/yab/us/Yahoo_ab.csv?loc=us&.rand=1671497644&A=H&Yahoo_ab.csv";

   private const string _authUrl = "https://login.yahoo.com/config/login?";

   private const string _loginPage = "https://login.yahoo.com/config/login";

   private const string _userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";

   private string username = string.Empty;

   private string password = string.Empty;


   protected void Page_Load(object sender, EventArgs e)

   {


   }


   private ArrayList Extract(string uname, string upass)

   {

     bool result = false;

     ArrayList myarray = new ArrayList();



     //list = New MailContactList()


     try

     {

       WebClient webClient = new WebClient();

       webClient.Headers[HttpRequestHeader.UserAgent] = _userAgent;

       webClient.Encoding = Encoding.UTF8;


       byte[] firstResponse = webClient.DownloadData(_loginPage);

       string firstRes = Encoding.UTF8.GetString(firstResponse);



       NameValueCollection postToLogin = new NameValueCollection();

       Regex regex = new Regex("type=\"hidden\" name=\"(.*?)\" value=\"(.*?)\"", RegexOptions.IgnoreCase);

       Match match = regex.Match(firstRes);

       while (match.Success)

       {

         if (match.Groups[0].Value.Length > 0)

         {

           postToLogin.Add(match.Groups[1].Value, match.Groups[2].Value);

         }

         match = regex.Match(firstRes, match.Index + match.Length);

       }



       postToLogin.Add(".save", "Sign In");

       postToLogin.Add(".persistent", "y");


       //Dim login As String = credential.UserName.Split("@"c)(0)

       string login = uname.Split('@').GetValue(0).ToString();


       postToLogin.Add("login", login);

       postToLogin.Add("passwd", upass);


       webClient.Headers[HttpRequestHeader.UserAgent] = _userAgent;

       webClient.Headers[HttpRequestHeader.Referer] = _loginPage;

       webClient.Encoding = Encoding.UTF8;

       webClient.Headers[HttpRequestHeader.Cookie] = webClient.ResponseHeaders[HttpResponseHeader.SetCookie];


       webClient.UploadValues(_authUrl, postToLogin);

       string cookie = webClient.ResponseHeaders[HttpResponseHeader.SetCookie];


       //If String.IsNullOrEmpty(cookie) Then

       //Return False

       //End If


       string newCookie = string.Empty;

       string[] tmp1 = cookie.Split(',');

       foreach (string var in tmp1)

       {

         string[] tmp2 = var.Split(';');

         newCookie = (String.IsNullOrEmpty(newCookie) ? tmp2[0] : newCookie + ";" + tmp2[0]);

       }


       // set login cookie

       webClient.Headers[HttpRequestHeader.Cookie] = newCookie;

       byte[] thirdResponse = webClient.DownloadData(_addressBookUrl);

       string thirdRes = Encoding.UTF8.GetString(thirdResponse);


       string crumb = string.Empty;

       Regex regexCrumb = new Regex("type=\"hidden\" name=\"\\.crumb\" id=\"crumb1\" value=\"(.*?)\"", RegexOptions.IgnoreCase);

       match = regexCrumb.Match(thirdRes);

       if (match.Success && match.Groups[0].Value.Length > 0)

       {

         crumb = match.Groups[1].Value;

       }



       NameValueCollection postDataAB = new NameValueCollection();

       postDataAB.Add(".crumb", crumb);

       postDataAB.Add("vcp", "import_export");

       postDataAB.Add("submit[action_export_yahoo]", "Export Now");


       webClient.Headers[HttpRequestHeader.UserAgent] = _userAgent;

       webClient.Headers[HttpRequestHeader.Referer] = _addressBookUrl;


       byte[] FourResponse = webClient.UploadValues(_addressBookUrl, postDataAB);

       string csvData = Encoding.UTF8.GetString(FourResponse);


       string[] lines = csvData.Split('\n');

       //Dim list1 As Hashtable()


       foreach (string line in lines)

       {

         string[] items = line.Split(',');

         if (items.Length < 5)         {           continue;         }         string email = items[4];         string name = items[3];         if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(name))         {           email = email.Trim('"');           name = name.Trim('"');           if (!email.Equals("Email") && !name.Equals("Nickname"))           {             MailContact mailContact = new MailContact();             mailContact.Name = name;             mailContact.Email = email;             myarray.Add(email);             //list.Add(mailContact)             }           }       }        result = true;     }     catch     {     }     return myarray;   }      protected void btnSubmit_Click(object sender, EventArgs e)   {     ArrayList contacts = new ArrayList();     StringBuilder sb = new StringBuilder();     contacts = Extract(txtusername.Text.Trim(), txtpassword.Text.Trim());     int j = 1;     for (int i = 0; i < contacts.Count; i++)     {       if (contacts[i].ToString().Trim() != "")       {           sb.Append("(" + j + ") " + contacts[i].ToString() + "

");

         j++;

       }

     }

     dvcontacts.InnerHtml = sb.ToString();

   }

}

public class MailContact

{

   private string _email = string.Empty;

   private string _name = string.Empty;


   public string Name

   {

     get { return _name; }

     set { _name = value; }

   }


   public string Email

   {

     get { return _email; }

     set { _email = value; }

   }


   public string FullEmail

   {

     get { return Email; }

   }

}



Hemanth Kumar replied to sonu Ranjan on 03-Dec-12 04:18 AM
Hi Sonu,

 Did you debug the code ? I found fews link for importing the yahoo contacts using C#

http://stackoverflow.com/questions/3002967/c-sharp-library-that-extracts-gmail-yahoomail-and-aol-contacts

http://stackoverflow.com/questions/5640423/yahoo-contacts-api-asp-net-c-sharp
sonu Ranjan replied to Lalit M on 09-Dec-12 01:53 AM
i am using this code and I Revive the Result (1) sans-serif;*font-size:small;*font:x-small;}(2) X(3) pv$1(4) pv$1

this is code Return value...
thanks to Help But  this code is not Return a proper value...