读取Exchange的用户未读邮件数3种办法
1、开通IMAP服务,采用IMAP方法读取,需要提供用户和密码
IMAP_Client imap = new IMAP_Client(); //链接 imap.Connect(server, port, ssl); //账户需要加上后缀名称,组合成"username@bzy.com"格式 // account = string.Format("{0}{1}", account,ExchangeManageConfig.ExchangeDomail); //验证账户 imap.Authenticate(account, password);
2、采用EWS读取邮件,默认取当前用户的登录认证方式(或提供用户和密码)
// // TODO: 在此处添加构造函数逻辑 //实例化对象 _esb = new ExchangeServiceBinding(); //授权-默认权限 ICredentials creds = System.Net.CredentialCache.DefaultNetworkCredentials; _esb.Credentials = creds; /设置webservice的URL _esb.Url = ExchangeManageConfig.ExchangeWebUrl;
3、采用EWS API方式。授权一个账户有模拟其他用户的权限
1.安装 Exchange Web Services Managed API,当前版本1.1 2.授权一个账户有模拟其他用户的权限,打开Exchange 2010 服务器在命令行中输入 New-ManagementRoleAssignment -Name:impersonationAssignmentName -Role:ApplicationImpersonation -User:serviceAccount serviceAccount:就是我们要模拟其他人的账户
protected void Page_Load(object sender, EventArgs e) { EwsConfig config = new EwsConfig(); config.ExchangeVersion=ExchangeVersion.Exchange2010_SP1; config.EWSServiceUrl="https://********/EWS/exchange.asmx"; config.ExchangeAdministrator = "<UserName>"; config.ExchangeAdministratorPassword = "<PWD>"; config.DomainName = "<domainName>"; config.OtherUserName = "<otherUserName>"; //下面这句屏蔽服务器证书验证,防止页面报“根据验证过程,远程证书无效”的错误 ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; }; ExchangeService service = new ExchangeService(config.ExchangeVersion); service.Credentials = new NetworkCredential(config.ExchangeAdministrator, config.ExchangeAdministratorPassword, config.DomainName); service.Url = new Uri(config.EWSServiceUrl); //前提打开Exchange 2010服务器在命令行中输入: //New-ManagementRoleAssignment -Name:impersonationAssignmentName -Role:ApplicationImpersonation -User:<UserName> service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.PrincipalName, config.OtherUserName); int unRead=Folder.Bind(service, WellKnownFolderName.Inbox).UnreadCount; HttpContext.Current.Response.Write(config.OtherUserName+"未读邮件数:"+unRead); } public struct EwsConfig { public ExchangeVersion ExchangeVersion; public string EWSServiceUrl; public string ExchangeAdministrator; public string ExchangeAdministratorPassword; public string DomainName; public string OtherUserName; }