读取Exchange邮件或任务(2)--通过Exchange Web Service Managed API

 

在上篇文章中介绍了通过Exchange Web Service来读取用户邮件或任务信息,大家可以看到需要写的代码很多且也比较复杂。接下介绍读取Exchange邮件或任务的第二种方法---通过Exchange Web Service Managed API 1.1.

 

Exchange Web Service Managed API:是微软提供的通过Exchange Web Service开发客户端应用程序来快速读取Exchange邮件、任务、发送邮件、删除邮件等的管理接口。

 

使用API的好处:

1、不用需要引用Exchange Web Service

2、代码量大大减少,提高开发效率

3、提高性能且更简单容易的对Exchange进行管理和操作

 

下载地址:http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c3342fb3-fbcc-4127-becf-872c746840e1

 

通过API来读取Exchange的邮件或任务的实现过程,如下:

1、引用如下命名空间:

using Microsoft.Exchange.WebServices.Data;

using System.Net;

using System.Net.Security;

using System.Security.Authentication;

using System.Security.Cryptography.X509Certificates;

 

2、实现代码

 

        /// <summary>
        
/// 读取所有Exchange对象数目,不使用模拟功能
        
/// </summary>
        
/// <param name="serverName">服务器名称</param>
        
/// <param name="useAutodiscover">是否自动发现服务器URL</param>
        public void EWSImpersonations(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
            
//建立信任连接
                
//ICredentials creds = CredentialCache.DefaultNetworkCredentials;
                    ICredentials creds = new NetworkCredential("username""password""domain");
                service.Credentials 
= new WebCredentials(creds);

                
if (!useAutodiscover)
                {
                    
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;
            
            
//创建读取信息视图
                ItemView view = new ItemView(10);
                view.OrderBy.Add(ItemSchema.DateTimeReceived, Microsoft.Exchange.WebServices.Data.SortDirection.Descending);

                
#region ReadEmail

                Folder inbox 
= Folder.Bind(service, WellKnownFolderName.Inbox);//Inbox文件夹,不包括子文件夹
                int unread = inbox.UnreadCount;

                Microsoft.Exchange.WebServices.Data.EmailMessage em 
= null;

                FindItemsResults
<Item> findMailResults = service.FindItems(WellKnownFolderName.Inbox, view);
                Response.Write(
"<br>unread mail subject: <br><br>");

                
foreach (Item m in findMailResults)
                {
                    em 
= (Microsoft.Exchange.WebServices.Data.EmailMessage)m;
                    
if (!em.IsRead)
                    {
                        Response.Write(em.Subject 
+ string.Format("  发件人: {0} <br>", em.From.Name.ToString()));
                    }
                }

                
//find all child folders mail message
                FindInboxChildFolders(service, view, serverName, ref unread);

                Response.Write(
"unread mail : " + unread.ToString() + "<br>");

                
#endregion

                Response.Write(
"==================================================");

                
#region ReadTask

                
int newTasks = 0;//unread task number
                FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Tasks,view); //读取任务文件夹,不包括子文件夹
                Microsoft.Exchange.WebServices.Data.Task t = null;

                Response.Write(
"<br>unread task subject:<br>");

                
foreach (Item item in findResults.Items)
                {
                    t 
= (Microsoft.Exchange.WebServices.Data.Task)(item);
                    
if (!t.IsComplete)
                    {
                        newTasks
++;

                        Response.Write(t.Subject);

                        Response.Write(
"<br>status :" + t.Status);
                    }
                }

                
//Find all task child folder
                FindTaskChildFolders(service, view, serverName, ref newTasks);

                Response.Write(
"<br><br> unread task :" + newTasks.ToString());

                
#endregion
            }
            
catch (Exception ex)
            {
                Response.Write(errorMessage);
            }
        }

        
/// <summary>
        
/// Find all child folder mail message
        
/// </summary>
        
/// <param name="service"></param>
        
/// <param name="view"></param>
        
/// <param name="serverName"></param>
        
/// <param name="unread"></param>
        private void FindInboxChildFolders(ExchangeService service, ItemView view, string serverName, ref int unread)
        {
            
try
            {
                FindFoldersResults findResults 
= service.FindFolders(WellKnownFolderName.Inbox,new FolderView(int.MaxValue));
                Microsoft.Exchange.WebServices.Data.EmailMessage em 
= null;
                
foreach (Folder folder in findResults.Folders)
                {
                    FindItemsResults
<Item> findMailResults = folder.FindItems(view);
                    unread 
+= folder.UnreadCount;
                    
foreach (Item m in findMailResults)
                    {
                        em 
= (Microsoft.Exchange.WebServices.Data.EmailMessage)m;
                        
if (!em.IsRead)
                        {
                            Response.Write(em.Subject 
+ string.Format("  发件人: {0} <br>", em.From.Name.ToString()));
                        }
                    }
                }
            }
            
catch
            {
            }

        }

        
/// <summary>
        
/// Find all task child folder
        
/// </summary>
        
/// <param name="service"></param>
        
/// <param name="view"></param>
        
/// <param name="serverName"></param>
        
/// <param name="newTasks"></param>
        private void FindTaskChildFolders(ExchangeService service, ItemView view, string serverName, ref int newTasks)
        {
            
try
            {
                FindFoldersResults findResults 
= service.FindFolders(WellKnownFolderName.Tasks,new FolderView(int.MaxValue));

                Microsoft.Exchange.WebServices.Data.Task t 
= null;

                
foreach (Folder folder in findResults.Folders)
                {
                    FindItemsResults
<Item> findTaskResults = folder.FindItems(view);
                    
foreach (Item task in findTaskResults)
                    {
                        t 
= (Microsoft.Exchange.WebServices.Data.Task)(task);
                        
if (!t.IsComplete)
                        {
                            newTasks
++;

                            Response.Write( t.Subject );

                            Response.Write(
"<br>status :" + t.Status);
                        }
                    }
                }
            }
            
catch (Exception)
            {
            }
        }

        
#endregion

        
/// <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;
        }

 

3、编译运行程序,读取邮件或任务

posted @ 2011-05-31 01:00  netcai  阅读(2775)  评论(11编辑  收藏  举报