一种读取Exchange的用户未读邮件数方法!

时间:2022-09-24 13:49:54

   已好几个月没写博客了,由于之前忙于开发基于Sharepoint上的移动OA(AgilePoint)和采用混合移动开发技术开发一个安卓版的企业通讯录APP(数据与lync一致),并于1月初正式上线。马年初二的时候,有个天津的网友加我QQ,说我之前发表博客SharePoint 2013中修改windows 活动目录(AD)域用户密码的WebPart(免费下载),的确对他有帮助,要捐助78元给我,希望我多发表相关的经验总结分享,本人深受鼓舞,并把修改AD域用户密码发他参考学习研究,并在初五合作了另外的Sharepoint 2013开发需求,并通过淘宝支付了定金,能够帮助他人解决问题,得到他人的认可还是蛮开心的。

   今天分享一下在1月初完成的KMS与OA的门户整合中其中用到的一种读取Exchange的用户未读邮件数方法,由于KMS是基于Java开发的,并且通过Cas已实现了SSO,需要通过接口把当前登录用户的未读取邮件数显示在KMS中,点击直接进入到OWA页面,如下图:

   一种读取Exchange的用户未读邮件数方法!

   本文主要通过采用EWS API方式自定义开发一个Web服务,并授权一个账户有模拟其他用户的权限,具体如下:

   1.安装Microsoft Exchange Web Services Managed API 2.0,下载地址如下:

     http://www.microsoft.com/en-us/download/details.aspx?id=35371

     一种读取Exchange的用户未读邮件数方法!

    2.0版本支持Exchange Server 2007 Service Pack 1以上,即包括Exchange Server 2010 Service和 Exchange Server 2013 Service。

   2.在Exchange服务器中授权一个账户有模拟其他用户的权限,具体如下:

      以Exchange 2010 Server为例,比如授权spadmin账号模拟其他用户的权限,打开Exchange 2010服务器在命令行中输入:

       New-ManagementRoleAssignment -Name:impersonationAssignmentName -Role:ApplicationImpersonation -User:spadmin

    3.利用EWS API开发一个自定义的读取Exchange的用户未读邮件数Web服务,已供其他系统(如KMS)调用,完整的C#代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Services.Description;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using ExchangeWebService.ews;


namespace ExchangeWebService
{
/// <summary>
/// Exchange Web Service by 软件人生 2013.12.31
/// </summary>
[WebService(Namespace = "http://www.cnblogs.com/nbpowerboy/exchange/")]
[WebServiceBinding(ConformsTo
= WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(
false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class ExchangeWebService : System.Web.Services.WebService
{

/// <summary>
/// 返回默认登录域用户的未读邮件数
/// </summary>
/// <returns>返回默认登录域用户的未读邮件数</returns>
[SoapRpcMethod(Action = "http://www.cnblogs.com/nbpowerboy/exchange/GetUserUnReadMailCount", RequestNamespace = "http://www.cnblogs.com/nbpowerboy/exchange/", ResponseNamespace = "http://www.cnblogs.com/nbpowerboy/exchange/", Use = SoapBindingUse.Literal)]
[WebMethod]
public int GetUserUnReadMailCount(string username, string password, string domain)
{


int merCurrentCount = 0;

try
{
ServicePointManager.ServerCertificateValidationCallback
= delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };

ExchangeServiceBinding service
= new ExchangeServiceBinding();

service.RequestServerVersionValue
= new RequestServerVersion();
service.RequestServerVersionValue.Version
= ExchangeVersionType.Exchange2010_SP2;
service.EnableDecompression
= true;
System.Net.NetworkCredential nc
= new NetworkCredential(username,password,domain);
//ICredentials creds = System.Net.CredentialCache.DefaultNetworkCredentials;
service.Credentials = nc;

service.Url
= @"https://mailserver/EWS/exchange.asmx";



merCurrentCount
= GetUnreadFolderItemsCount(service, "收件箱");

}
catch
{

}


return merCurrentCount;
}

/// <summary>
/// 根据用户邮件地址返回用户的未读邮件数
/// </summary>
/// <returns>根据用户邮件地址返回用户的未读邮件数</returns>
[SoapRpcMethod(Action = "http://www.cnblogs.com/nbpowerboy/exchange/GetUnReadMailCountByUserMailAddress", RequestNamespace = "http://www.cnblogs.com/nbpowerboy/exchange/", ResponseNamespace = "http://www.cnblogs.com/nbpowerboy/exchange/", Use = SoapBindingUse.Literal)]
[WebMethod]
public int GetUnReadMailCountByUserMailAddress(string UserMailAddress)
{

int unRead = 0;

try
{

Microsoft.Exchange.WebServices.Data.ExchangeService service
= new Microsoft.Exchange.WebServices.Data.ExchangeService(Microsoft.Exchange.WebServices.Data.ExchangeVersion.Exchange2010_SP2);
service.Credentials
= new NetworkCredential("spadmin", "Password", "contoso");
service.Url
= new Uri(@"https://mailserver/EWS/exchange.asmx");



service.ImpersonatedUserId
= new Microsoft.Exchange.WebServices.Data.ImpersonatedUserId(Microsoft.Exchange.WebServices.Data.ConnectingIdType.SmtpAddress, UserMailAddress);




unRead
= Microsoft.Exchange.WebServices.Data.Folder.Bind(service, Microsoft.Exchange.WebServices.Data.WellKnownFolderName.Inbox).UnreadCount;
}
catch
{

}

return unRead;
}


/// <summary>
/// 根据用户名返回用户的未读邮件数
/// </summary>
/// <returns>根据用户邮件地址返回用户的未读邮件数</returns>
[SoapRpcMethod(Action = "http://www.cnblogs.com/nbpowerboy/exchange/GetUnReadMailCountByUserPrincipalName", RequestNamespace = "http://www.cnblogs.com/nbpowerboy/exchange/", ResponseNamespace = "http://www.cnblogs.com/nbpowerboy/exchange/", Use = SoapBindingUse.Literal)]
[WebMethod]
public int GetUnReadMailCountByUserPrincipalName(string UserPrincipalName)
{

int unRead = 0;

try
{

Microsoft.Exchange.WebServices.Data.ExchangeService service
= new Microsoft.Exchange.WebServices.Data.ExchangeService(Microsoft.Exchange.WebServices.Data.ExchangeVersion.Exchange2010_SP2);
service.Credentials
= new NetworkCredential("spadmin", "Password", "contoso");
service.Url
= new Uri(@"https://mailserver/EWS/exchange.asmx");



service.ImpersonatedUserId
= new Microsoft.Exchange.WebServices.Data.ImpersonatedUserId(Microsoft.Exchange.WebServices.Data.ConnectingIdType.PrincipalName, UserPrincipalName);




unRead
= Microsoft.Exchange.WebServices.Data.Folder.Bind(service, Microsoft.Exchange.WebServices.Data.WellKnownFolderName.Inbox).UnreadCount;
}
catch
{

}

return unRead;
}


private static int GetUnreadFolderItemsCount(ExchangeServiceBinding service, string folderName)
{
try
{
int unReadCount = -1;
// Identify the folder properties to return.
FolderResponseShapeType properties = new FolderResponseShapeType();
PathToUnindexedFieldType ptuft
= new PathToUnindexedFieldType();
ptuft.FieldURI
= UnindexedFieldURIType.folderManagedFolderInformation;
PathToUnindexedFieldType[] ptufts
= new PathToUnindexedFieldType[1] { ptuft };
properties.AdditionalProperties
= ptufts;
properties.BaseShape
= DefaultShapeNamesType.AllProperties;

// Form the get folder request.
BaseFolderIdType p_folder = FindFolderID(service, folderName);

GetFolderType request
= new GetFolderType();
request.FolderIds
= new BaseFolderIdType[1] { p_folder };
request.FolderShape
= properties;

// Send the request and get the response.
GetFolderResponseType response = service.GetFolder(request);

ArrayOfResponseMessagesType aormt
= response.ResponseMessages;
ResponseMessageType[] rmta
= aormt.Items;
foreach (ResponseMessageType rmt in rmta)
{
if (rmt.ResponseClass == ResponseClassType.Error)
{
throw new Exception(rmt.MessageText);
}
else
{
FolderInfoResponseMessageType firmt;
firmt
= (rmt as FolderInfoResponseMessageType);
BaseFolderType[] folders
= firmt.Folders;

foreach (BaseFolderType rfolder in folders)
{
if (rfolder is FolderType)
{
FolderType myFolder;
myFolder
= (rfolder as FolderType);
if (myFolder.UnreadCountSpecified)
{
unReadCount
= myFolder.UnreadCount;
}
}
}
}
}
return unReadCount;
}
catch
{
return 0;
}
}

private static FolderIdType FindFolderID(ExchangeServiceBinding service, String folderName)
{
DistinguishedFolderIdType objSearchRootFolder
= new DistinguishedFolderIdType();
objSearchRootFolder.Id
= DistinguishedFolderIdNameType.msgfolderroot;

FindFolderType requestFindFolder
= new FindFolderType();
requestFindFolder.Traversal
= FolderQueryTraversalType.Deep;
requestFindFolder.ParentFolderIds
= new DistinguishedFolderIdType[] { objSearchRootFolder };
requestFindFolder.FolderShape
= new FolderResponseShapeType();
requestFindFolder.FolderShape.BaseShape
= DefaultShapeNamesType.IdOnly;

//Search filter definition
requestFindFolder.Restriction = new RestrictionType();

#region Contains expression

ContainsExpressionType objContainsExpression
= new ContainsExpressionType();
objContainsExpression.ContainmentMode
= ContainmentModeType.FullString;
objContainsExpression.ContainmentModeSpecified
= true;
objContainsExpression.ContainmentComparison
= ContainmentComparisonType.Exact;
objContainsExpression.ContainmentComparisonSpecified
= true;

PathToUnindexedFieldType objFieldFolderName
= new PathToUnindexedFieldType();
objFieldFolderName.FieldURI
= UnindexedFieldURIType.folderDisplayName;
objContainsExpression.Item
= objFieldFolderName;

objContainsExpression.Constant
= new ConstantValueType();
objContainsExpression.Constant.Value
= folderName;

#endregion Contains expression

requestFindFolder.Restriction.Item
= objContainsExpression;

FindFolderResponseType objFindFolderResponse
=
service.FindFolder(requestFindFolder);

if (objFindFolderResponse.ResponseMessages.Items.Length == 0)
return null;

foreach (ResponseMessageType responseMsg in
objFindFolderResponse.ResponseMessages.Items)
{
if (responseMsg.ResponseClass == ResponseClassType.Success)
{
FindFolderResponseMessageType objFindResponse
=
responseMsg
as FindFolderResponseMessageType;
foreach (
BaseFolderType objFolderType
in objFindResponse.RootFolder.Folders)
{
return objFolderType.FolderId;
}
}
}
return null;
}


}
}

 

本博客为软件人生原创,欢迎转载,转载请标明出处:http://www.cnblogs.com/nbpowerboy/p/3539422.html 。演绎或用于商业目的,但是必须保留本文的署名软件人生(包含链接)。如您有任何疑问或者授权方面的协商,请给我留言。