我正在从c#中添加活动目录用户,并且需要使用Exchange Mail Server为该用户创建电子邮件ID。
如何使用c#检查和创建新的邮件ID?答案 0 :(得分:0)
我已经做到了,这很痛苦。在Exchange中以编程方式执行任何操作的唯一方法是通过PowerShell,这意味着您必须从C#运行PowerShell命令。
理想情况下,您可以打开到其中一台Exchange服务器的远程PowerShell会话。 Microsoft确实在此处提供了如何执行此操作的示例:Get a list of mail users by using the Exchange Management Shell。
创建远程PowerShell会话将类似于以下内容,该会话使用Kerberos进行身份验证并运行PowerShell命令Get-Users -ResultSize 10
:
var connectionUri = "https://<server>/PowerShell";
var remoteMachineCredentials = new PSCredential(domainAndUserName, securePassword);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(
new Uri(connectionUri),
"http://schemas.microsoft.com/powershell/Microsoft.Exchange",
remoteMachineCredentials) {
AuthenticationMechanism = AuthenticationMechanism.Kerberos,
SkipRevocationCheck = true
}
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo)) {
using (PowerShell powershell = PowerShell.Create()) {
powershell.AddCommand("Get-Users");
powershell.AddParameter("ResultSize", 10);
runspace.Open();
powershell.Runspace = runspace;
var results = powershell.Invoke();
//do something with the results
}
}
如果需要的话,您也可以使用AuthenticationMechanism.NegotiateWithImplicitCredential
来验证应用运行时所使用的凭据。
我使用SkipRevocationCheck = true
来跳过服务器SSL证书的吊销检查。在我的环境中,我在其上运行的服务器没有Internet访问,因此吊销检查失败。这可能对您来说不正确。
您可以完成此操作,而无需使用远程PowerShell,但这需要在运行您的应用的计算机上安装Exchange管理工具,并且还存在其他一些复杂问题。尽量避免这种情况。如果可以,请使用远程PowerShell。
确定了这一点之后,就可以运行任何PowerShell命令,例如New-Mailbox
。
您当然希望阅读PowerShell响应的结果,因此还有另一篇文章介绍如何Use the Exchange Management Shell cmdlet response。
请注意,PowerShell错误默认不会终止(它们不会引发异常),因此,每次运行命令时,您都必须检查是否存在错误。为此,请检查powershell.Streams.Error
集合。