Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a user's e-mail address from Active Directory?

I am trying to get a user's email address in AD without success.

String account = userAccount.Replace(@"Domain\", ""); DirectoryEntry entry = new DirectoryEntry();  try {     DirectorySearcher search = new DirectorySearcher(entry);      search.PropertiesToLoad.Add("mail");  // e-mail addressead      SearchResult result = search.FindOne();     if (result != null) {         return result.Properties["mail"][0].ToString();     } else {         return "Unknown User";     } } catch (Exception ex) {     return ex.Message; } 

Can anyone see the issue or point in the right direction?

like image 735
user95440 Avatar asked Apr 24 '09 11:04

user95440


People also ask

What is the email attribute in Active Directory?

Mail attribute: Holds the primary email address of a user, without the SMTP protocol prefix. For example, [email protected] . MailNickName attribute: Holds the alias of an Exchange recipient object.

How do I find my SMTP address in Active Directory?

Find SMTP addresses in Active DirectoryGo to the user object properties and click on the attribute editor tab. Find the attribute proxyAddresses. The same two SMTP email addresses are shown as values, just like we saw earlier in the Exchange Admin Center. You have seen the SMTP addresses in both places.


1 Answers

Disclaimer: This code doesn't search for a single exact match, so for domain\j_doe it may return domain\j_doe_from_external_department's email address if such similarly named account also exists. If such behaviour is undesirable, then either use a samAccountName filter intead of an anr one used below or filter the results additionally.

I have used this code successfully (where "account" is the user logon name without the domain (domain\account):

// get a DirectorySearcher object DirectorySearcher search = new DirectorySearcher(entry);  // specify the search filter search.Filter = "(&(objectClass=user)(anr=" + account + "))";  // specify which property values to return in the search search.PropertiesToLoad.Add("givenName");   // first name search.PropertiesToLoad.Add("sn");          // last name search.PropertiesToLoad.Add("mail");        // smtp mail address  // perform the search SearchResult result = search.FindOne(); 
like image 56
Fredrik Mörk Avatar answered Oct 17 '22 07:10

Fredrik Mörk