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 an Exchange server. 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://exchangeserver", //Make sure to point this at your exchange 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();
}
}
}
}
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. You might get the name of a user from the GAL, from getting a list of members of a group, etc. Or you may simply be given the name by the user. 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, etc.
a83bd706-1f4a-409e-9c1e-d2a57fbcbbaf|0|.0