Other Posts in LDAP

  1. Getting a User's Email Address from Active Directory
  2. Getting Names and Email Addresses from Active Directory Groups
  3. Getting All Contact Information from Active Directory
  4. Active Directory Utility for C#/ASP.Net
  5. Scanning a Network for Computers in C#

Getting a User's Email Address from Active Directory

3/14/2008

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:

   1: public static string GetUsersEmail(string User, string UserName, string Password)
   2: {
   3:    string EmailAddress = "";
   4:    DirectoryEntry Entry = new DirectoryEntry("LDAP://ADserver",   //Make sure to point this at your AD server
   5:                                                UserName,
   6:                                                Password,
   7:                                                AuthenticationTypes.Secure);
   8:    DirectorySearcher Searcher = new DirectorySearcher(Entry);
   9:    Searcher.PropertiesToLoad.Add("mail");
  10:    string Filter = String.Format("(&(objectcategory=user)(cn=" + User + "))"); 
  11:  
  12:    Searcher.Filter = Filter;
  13:    Searcher.Sort.Direction = SortDirection.Ascending;
  14:    Searcher.Sort.PropertyName = "cn"; 
  15:  
  16:    SearchResultCollection Results; 
  17:  
  18:    Results = Searcher.FindAll(); 
  19:  
  20:    foreach (SearchResult Result in Results)
  21:    {
  22:       ResultPropertyCollection Properties = Result.Properties;
  23:       foreach (string Key in Properties.PropertyNames)
  24:       {
  25:          if (Key == "mail")
  26:          {
  27:             foreach (object Values in Properties[Key])
  28:             {
  29:                EmailAddress = Values.ToString();
  30:                break;
  31:             }
  32:          }
  33:       }
  34:    }
  35:    return EmailAddress;
  36: }

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.



Comments