查询 Exchange 服务器并从 NT 用户名检索电子邮件地址






1.86/5 (3投票s)
2007年8月13日

41674

46
这是一个简单的方法,用于查询 Exchange 服务器并在公司内部网中检索远程用户的电子邮件地址。
引言
在搜索了许多不同的文章后,我终于能够实现我想要的功能了。我想在公司内部网中使用户在点击网页上的提交按钮时,无需使用 Outlook 就能发送电子邮件。听起来很简单,对吧?
我发现最好的方法是使用目录服务。因此,在你的 ASP .NET 应用程序中,右键单击解决方案资源管理器中的根节点,并在 .NET 选项卡上添加一个引用到
System.DirectoryServices
然后,在 using 语句中包含以下内容。完成这些操作后,剩下的就比较容易了。
//
// I created a simple class to be available anywhere in the application:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.DirectoryServices;
using System.Collections;
public class NTtoEmail
{
public NTtoEmail()
{
}
public string GetEmail(string ntname)
{
DirectorySearcher objsearch = new DirectorySearcher();
string strrootdse = objsearch.SearchRoot.Path;
DirectoryEntry objdirentry = new DirectoryEntry(strrootdse);
objsearch.Filter = "(& (mailnickname="+ ntname.Trim() + ")(objectClass=user))";
objsearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
objsearch.PropertiesToLoad.Add("mail");
objsearch.PropertyNamesOnly = true;
SearchResultCollection colresults = objsearch.FindAll();
string arl = "";
foreach (SearchResult objresult in colresults)
{
arl = arl + objresult.GetDirectoryEntry().Properties["mail"].Value + ",";
}
if (arl.Length > 0)
arl = arl.Substring(0, arl.Length - 1);
objsearch.Dispose();
return arl;
}
}
这很简单。现在你可以像这样从网页中调用它:
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { NTtoEmail mlc = new NTtoEmail(); TextBox1.Text = mlc.GetEmail(Request.ServerVariables["REMOTE_USER"].Substring(3, Request.ServerVariables["REMOTE_USER"].Length - 3)); } }
关注点
ServerVariables 返回域名。我们的公司域名是 2 个字母,所以这可以正常工作,但如果你有多个域名,我建议使用 split 函数。
也欢迎查看我的网站:
http://www.dbaoasis.com