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:

string getEmail( string userName )
{
  // Set the correct format for the AD query and filter
  string ldapEntry = "LDAP://" + "<domain name>";
  string loginName = "<domain login>";
  string loginPassword = "<domain password>";SearchResult result = null;

  using (DirectoryEntry root = new DirectoryEntry(ldapEntry, loginName, loginPassword))
  {
    using (DirectorySearcher searcher = new DirectorySearcher(root))
    {
      try
      {
        searcher.Filter = "(SAMAccountName="+userName+")";
        searcher.PropertiesToLoad.Add("mail");
        SearchResultCollection results = searcher.FindAll();
        result = (results.Count != 0) ? results[0] : null;
      }
      catch (Exception ex)
      {
        return "<not found>";;
      }
    }
  }
  return result.Properties["mail"][0] as string;
}

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.

no comments yet.

Leave a comment

Names and email addresses are required (email addresses aren't displayed), url's are optional.

Comments may contain the following xhtml tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>