参考资料: http://www.dotblogs.com.tw/wadehuang36/archive/2012/07/04/ews-first.aspx
本範例的主要功能是尋找未讀郵件並下載附件、完成更新成已讀並移動資料夾
view source print ?
01 | internal class Program |
03 | private static void Main( string [] args) |
05 | ExchangeService es = new ExchangeService(ExchangeVersion.Exchange2007_SP1); //版本預設值最新版 |
06 | es.Credentials = new WebCredentials( "username" , "password" , "domain" ); |
07 | //es.Credentials = new ClientCertificateCredentials(x509); 也可以使用憑證登入 |
09 | es.Url = new Uri( "https://server/EWS/Exchange.asmx" ); // Server路徑 |
11 | Folder processedFolder = GetFolder(es); |
12 | SearchFilter search = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false ); //使用欄位搜尋 |
13 | //string search = "From:Wade AND Subject:EWS"; //也支援搜尋語法,但語法沒有IsRead欄位 |
16 | foreach (EmailMessage element in es.FindItems(WellKnownFolderName.Inbox, search, new ItemView(10))) |
18 | //跟IMAP一樣,首先只會下載部分基本資料,像Body與Attachments資訊要呼叫Load才會下載 |
19 | element.Load(PropertySet.FirstClassProperties); |
21 | foreach (FileAttachment item in element.Attachments) |
24 | item.Load( "R:\\" + item.Name); |
30 | element.IsRead = true ; |
31 | element.Update(ConflictResolutionMode.AlwaysOverwrite); |
34 | element.Move(processedFolder.Id); |
38 | private static Folder GetFolder(ExchangeService es) |
40 | //取得 處理完成資料夾,如果沒有資料夾就新增 |
41 | SearchFilter search = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "處理完成" ); |
43 | var folder = es.FindFolders(WellKnownFolderName.Inbox, search, new FolderView(1)).FirstOrDefault(); |
46 | folder = new Folder(es); |
47 | folder.DisplayName = "處理完成" ; |
48 | folder.Save(WellKnownFolderName.Inbox); //在Inbox下新增資料夾 |