Exchange Web Services Managed API 1.1很省事

如果想通过Exchange 2007/2010 EWS读取或者写入数据,比如快速读取未读邮件、任务等数目,读取邮件、任务标题等等,不用再去写那么多代码了,交给Exchange Web Services Managed API 吧,基本上你不怎么写代码了,而且安全。

如下示例: 以前代码:

GetFolderType request = new GetFolderType();

request.FolderShape = new FolderResponseShapeType();
request.FolderShape.BaseShape = DefaultShapeNamesType.AllProperties;

DistinguishedFolderIdType inboxId = new DistinguishedFolderIdType();
inboxId.Id = DistinguishedFolderIdNameType.inbox;

request.FolderIds = new BaseFolderIdType[] { inboxId };

GetFolderResponseType response = serviceBinding.GetFolder(request);
FolderInfoResponseMessageType responseMessage =
response.ResponseMessages.Items[0] as FolderInfoResponseMessageType;

if (responseMessage.ResponseClass == ResponseClassType.Success)
{
    FolderType inbox = responseMessage.Folders[0] as FolderType;
}

现在代码:

Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);

代码看起来简单清爽多了吧!!!接下来只要点点就是你想要的东西: unread = inbox.UnreadCount.ToString(); 

更多请参见如下代码示例片断:其中红色部分标示,WellKnownFolderName.Tasks;//任务或者收件箱等等,枚举搞定,如果想使用高级的账户模拟功能,可能需要更高级版本的Exchange 比如2010 SP1,如果达不到代码自动会报出错误,版本越低使用功能就越少。比如自动发现(不用写IP地址什么的就一个地址搞定):

ExchangeService service = new ExchangeService();
service.Credentials = new NetworkCredential("name", "pwd", "domain");
service.AutodiscoverUrl("someone@contoso.com");

看来已经很省事了呢。。。。以下是其它代码片断:

using System.Net;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

using Microsoft.Exchange.WebServices.Data;

//Call SSL Web service must added!!!
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

//"https://192.168.0.68/ews/exchange.asmx"
EWSImpersonation(U_Name + "@contoso.com", U_Pwd, "192.168.0.68", false);



  /// <summary>
    /// 读取所有Exchange对象数目,不使用模拟功能
    /// </summary>
    /// <param name="aemail">标准邮件地址</param>
    /// <param name="apwd">密码</param>
    /// <param name="serverName">服务器名称</param>
    /// <param name="useAutodiscover">是否自动发现服务器URL</param>
    public void EWSImpersonation(string aemail, string apwd, string serverName, bool useAutodiscover)
    {
        try
        {
            //Call SSL Web service must added!!!
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);//如果是Exchange 2010,则切换到2010
            service.Credentials = new WebCredentials(aemail, apwd);

            //service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, email);
            if (useAutodiscover)
                service.AutodiscoverUrl(aemail);
            else
            {
                string[] servers = serverName.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                for (int i = 0; i < servers.Length; i++)
                {
                    try
                    {
                        service.Url = new Uri("https://" + servers[i] + "/ews/exchange.asmx");
                        break;
                    }
                    catch
                    {
                    }
                }
            }

            service.PreAuthenticate = true;
            #region ReadEmail
            Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);//发件箱
            all = inbox.TotalCount.ToString();
            unread = inbox.UnreadCount.ToString();
            #endregion

            #region ReadTask
            //ItemView view = new ItemView(2048);
            //view.PropertySet = new PropertySet(BasePropertySet.IdOnly, TaskSchema.IsComplete);
            //SearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(TaskSchema.IsComplete, "False");

            TasksFolder tasks = TasksFolder.Bind(service, WellKnownFolderName.Tasks);//任务


            //FindItemsResults<Item> res = tasks.FindItems(filter, view);

            //SearchFolder searchFolder = new SearchFolder(service);
            //searchFolder.DisplayName = "My search folder";
            //searchFolder.SearchParameters.RootFolderIds.Add(WellKnownFolderName.Tasks);
            //searchFolder.SearchParameters.SearchFilter = new SearchFilter.SearchFilterCollection(
            //    LogicalOperator.And,
            //    new SearchFilter.IsEqualTo(TaskSchema.IsComplete, "false"));
            //searchFolder.Save(WellKnownFolderName.SearchFolders);

            allTasks = tasks.TotalCount.ToString();
            undo = tasks.TotalCount.ToString();//tasks.UnreadCount.ToString() aways = 0,so use TotalCount!!!!
            #endregion

        }
        catch (Exception ex)
        {
            isError = true;
            errorMessage = ex.Message + ex.StackTrace;

        }
    }

    /// <summary>
    /// 读取所有Exchange对象数目,使用模拟功能(Only for Exchange2010 or SP1)
    /// </summary>
    /// <param name="email">要模拟和读取用户的Eamil</param>
    /// <param name="aemail">管理员标准邮件地址</param>
    /// <param name="apwd">管理员密码</param>
    /// <param name="serverName">服务器名称</param>
    /// <param name="useAutodiscover">是否自动发现服务器URL</param>
    public void EWSImpersonation(string email, string aemail, string apwd, string serverName, bool useAutodiscover)
    {
        try
        {
            //Call SSL Web service must added!!!
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
            service.Credentials = new WebCredentials(aemail, apwd);

            service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, email);
            if (useAutodiscover)
                service.AutodiscoverUrl(aemail);
            else
            {
                string[] servers = serverName.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                for (int i = 0; i < servers.Length; i++)
                {
                    try
                    {
                        service.Url = new Uri("https://" + servers[i] + "/ews/exchange.asmx");
                        break;
                    }
                    catch
                    {
                    }
                }
            }

            service.PreAuthenticate = true;

            #region ReadEmail
            Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);//发件箱
            all = inbox.TotalCount.ToString();
            unread = inbox.UnreadCount.ToString();
            #endregion

            #region ReadTask
            Folder tasks = Folder.Bind(service, WellKnownFolderName.Tasks);//任务
            allTasks = tasks.TotalCount.ToString();
            undo = tasks.UnreadCount.ToString();
            #endregion

        }
        catch (Exception ex)
        {
            isError = true;
            errorMessage = ex.Message + ex.StackTrace;

        }
    }

    /// <summary>
    /// 忽略SSL证书请求
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="certificate"></param>
    /// <param name="chain"></param>
    /// <param name="errors"></param>
    /// <returns></returns>
    public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {
        return true;
    }
posted @ 2011-05-29 19:42  pccai  阅读(2267)  评论(7编辑  收藏  举报