Getting a User's Email Address from Active Directory

Or really any information from Active Directory...
Mar 14 2008 by James Craig

Let's say that you have a user's name and you want to send a bit of mail to them using an ASP.Net page. At the same time you have Active Directory set up on your network. By using the following function you can easily get that information:

 public static string GetUsersEmail(string User, string UserName, string Password)
{
string EmailAddress = "";
DirectoryEntry Entry = new DirectoryEntry("LDAP://ADserver", //Make sure to point this at your AD server
UserName,
Password,
AuthenticationTypes.Secure);
DirectorySearcher Searcher = new DirectorySearcher(Entry);
Searcher.PropertiesToLoad.Add("mail");
string Filter = String.Format("(&(objectcategory=user)(cn=" + User + "))");

Searcher.Filter = Filter;
Searcher.Sort.Direction = SortDirection.Ascending;
Searcher.Sort.PropertyName = "cn";

SearchResultCollection Results;

Results = Searcher.FindAll();

foreach (SearchResult Result in Results)
{
ResultPropertyCollection Properties = Result.Properties;
foreach (string Key in Properties.PropertyNames)
{
if (Key == "mail")
{
foreach (object Values in Properties[Key])
{
EmailAddress = Values.ToString();
break;
}
}
}
}
return EmailAddress;
}

All this function is doing is using LDAP to query the server for a user's information and specifically their email address. This function can come in handy more often than you think. With LDAP you can query for a user's name, get a list of distribution groups that they're members of, etc. In any case I've found that this comes in handy and I'll even show you in some future posts how to put this to good use. Anyway, feel free to use the code, leave comments, and happy coding.