C# - 查找 Active Directory 用户的所有电子邮件地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1609353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:21:50  来源:igfitidea点击:

C# - Find all email addresses for an Active Directory user

c#.netactive-directory

提问by pgb

I'm trying to get all the email addresses associated to a given AD user.

我正在尝试获取与给定 AD 用户关联的所有电子邮件地址。

For the user I have the domain and the login name (ex. DOMAIN\UserName) and I the AD is storing the email addresses in:

对于用户,我拥有域和登录名(例如 DOMAIN\UserName),并且我的 AD 将电子邮件地址存储在:

  1. The mail attribute.
  2. In proxyAddressesattributes.
  1. 邮件属性。
  2. proxyAddresses属性上。

So far, I don't know what C# API to use to connect to the AD, and how to properly filter by the user to fetch all the email addresses. I'm using .NET 3.5.

到目前为止,我不知道使用什么 C# API 来连接到 AD,以及如何由用户正确过滤以获取所有电子邮件地址。我正在使用 .NET 3.5。

Thank you.

谢谢你。

回答by JonH

Have you looked at the DirectoryEntry class. You can pull properties from there given you have the LDAP string set up. The propery for mail is "mail" ironic aint it ?

您是否看过 DirectoryEntry 类。如果您设置了 LDAP 字符串,则可以从那里提取属性。邮件的属性是“邮件”,这不是讽刺吗?

回答by Donut

Here's a possible solution using various classes in the System.DirectoryServicesnamespace.

这是使用System.DirectoryServices命名空间中的各种类的可能解决方案。

string username = "username";
string domain = "domain";

List<string> emailAddresses = new List<string>();

PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domain);
UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, username);

// Add the "mail" entry
emailAddresses.Add(user.EmailAddress);

// Add the "proxyaddresses" entries.
PropertyCollection properties = ((DirectoryEntry)user.GetUnderlyingObject()).Properties;
foreach (object property in properties["proxyaddresses"])
{
   emailAddresses.Add(property.ToString());
}