如何从Active Directory获取用户的电子邮件地址?

use*_*440 23 c# active-directory

我试图在AD中获取用户的电子邮件地址但没有成功.

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;
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以看到问题或指向正确的方向吗?

Fre*_*örk 40

我已成功使用此代码(其中"account"是没有域(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();
Run Code Online (Sandbox Code Playgroud)

  • 上面查询中的`anr`是"模糊名称解析",因此进行模糊匹配.如果你想要一个完全匹配,请在上面的代码中使用`sAMAccountName`而不是`anr` (4认同)
  • 是的,我也为我工作过.是的也需要调用语法... Response.Write(result.Properties ["givenName"] [0] .ToString()); 的Response.Write( "点击"); 回复于(result.Properties [ "SN"] [0]的ToString()); 的Response.Write( "点击"); 回复于(result.Properties [ "邮件"] [0]的ToString()); 的Response.Write( "点击"); 回复于(FindName( "gruberj")); (3认同)
  • 我不得不使用(&(objectCategory = person)(objectClass = user)(anr ="+ account +"))";因为第一个结果是我刚使用objectClass = user时的计算机 (3认同)

小智 11

你们太努力了:

// Look up the current user's email address
string eMail =  UserPrincipal.Current.EmailAddress;
Run Code Online (Sandbox Code Playgroud)

  • OP 没有询问是否查找当前用户的电子邮件 - 即使他们这样做,也假设该应用程序正在使用域身份验证。 (3认同)
  • 什么是“用户主体”?***命名空间和程序集***? (2认同)
  • 很好,需要对“System.DirectoryServices.AccountManagement”的引用,并且不需要像当前那样登录。 (2认同)
  • 您的帖子比原始答案晚了8年-但是,嘿,我现在正在寻找-所以我将在7分中使用1条线... (2认同)