在用ExchangeService(EWS)串連Exchange郵件伺服器時,報錯:
The response received from the service didn't contain valid XML.其InnerException為: The expected XML node type was XmlDeclaration, but the actual type is Element.其原始碼如下:
//串連伺服器 ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new NetworkCredential("***", "***", "***"); service.AutodiscoverUrl("***"); //擷取郵件清單(收件匣中的郵件) FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox,new ItemView(10)); foreach (Item item in findResults.Items) { //擷取具體的郵件對象 EmailMessage email = EmailMessage.Bind(service, item.Id); //判斷附件是否為檔案 if (!(email.Attachments[0] is FileAttachment)) continue; FileAttachment fileAttachment = email.Attachments[0] as FileAttachment; fileAttachment.Load("C:\\temp\\" + fileAttachment.Name); //標示讀取 email.IsRead = true; //將對郵件的改動提交到伺服器 email.Update(ConflictResolutionMode.AlwaysOverwrite); }
查了一些資料,也沒有找到具體的原因,自己嘗試了好多方法,最終將代碼更改如下:
//串連伺服器 ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new NetworkCredential("使用者名稱", "密碼", "域"); service.AutodiscoverUrl("你的郵箱"); service.Url = new Uri("這裡是你的郵箱Service地址(以asmx結尾)"); //擷取郵件清單(收件匣中的郵件) FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox,new ItemView(10)); foreach (Item item in findResults.Items) { //擷取具體的郵件對象 EmailMessage email = EmailMessage.Bind(service, item.Id); //判斷附件是否為檔案 if (!(email.Attachments[0] is FileAttachment)) continue; FileAttachment fileAttachment = email.Attachments[0] as FileAttachment; fileAttachment.Load("C:\\temp\\" + fileAttachment.Name); //標示讀取 email.IsRead = true; //將對郵件的改動提交到伺服器 email.Update(ConflictResolutionMode.AlwaysOverwrite); }
這一次就能正常收取了,加入了URL問題就解決了,不知道這個是什麼原因,我原來用第一段代碼的時候,並沒有加入Url也能夠正常訪問的,這個事情比較的奇怪。