问题描述
我试图在AD中获取用户的电子邮件地址,但没有成功。
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?
推荐答案
免责声明:此代码不会搜索,因此对于 domain\ j_doe
,如果还存在类似名称的帐户,则可能会返回 domain\j_doe_from_external_department
的电子邮件地址。如果不希望出现这种情况,请使用 在下面使用的一个,或过滤
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.
我已成功使用此代码(其中 account是不带域的用户登录名(domain\account) :
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();
这篇关于如何从Active Directory中获取用户的电子邮件地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!