Getting user’s email address from ASP.NET

Posted on January 2, 2007 by ZDima.
Categories: ASP.NET.

Today I was asked to use a real email ID instead of user login id. Apparently some people have a different login ID and email alias. So I decided to try to use a Request object, but I could not find the way to access required information. So I decided to try company’s Directory Service. After searching I found following solution:

  1. string getEmail( string userName )
  2. {
  3.   // Set the correct format for the AD query and filter
  4.   string ldapEntry = "LDAP://" + "<domain name>";
  5.   string loginName = "<domain login>";
  6.   string loginPassword = "<domain password>";SearchResult result = null;
  7.  
  8.   using (DirectoryEntry root = new DirectoryEntry(ldapEntry, loginName, loginPassword))
  9.   {
  10.     using (DirectorySearcher searcher = new DirectorySearcher(root))
  11.     {
  12.       try
  13.       {
  14.         searcher.Filter = "(SAMAccountName="+userName+")";
  15.         searcher.PropertiesToLoad.Add("mail");
  16.         SearchResultCollection results = searcher.FindAll();
  17.         result = (results.Count != 0) ? results[0] : null;
  18.       }
  19.       catch (Exception ex)
  20.       {
  21.         return "<not found>";;
  22.       }
  23.     }
  24.   }
  25.   return result.Properties["mail"][0] as string;
  26. }

Interestingly, I have to use user id and password to access DS. So I used dummy and/or very restricted user id and password just to gain access to DS.