2011-05-16 69 views
1

摘要: 我需要登錄到我的郵箱使用EWS,但我不斷收到440/401錯誤。c#ews登錄錯誤

問題: 我的代碼中有什麼顯而易見的,爲什麼我一直得到401或440錯誤?

代碼:

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Net; 
using Microsoft.Exchange.WebServices; 
using Microsoft.Exchange.WebServices.Data; 
using Microsoft.Exchange.WebServices.Autodiscover; 


namespace MailboxListenerEWS 
{ 
    class Program 
    { 
     //Authentication to exchange 2007 with webdav and filebasedauth (FBA) in C# 
     //can hardcode a username to connect a mailbox with 
     internal static string dUser = "username";//username to log into email account 
     internal static string dDomain = "domain";//domain of username used 
     internal static string dPassword = "Password";//password of username used 
     internal static string MailBoxAliasName = "mailboxname";//mailbox to authenticate too 
     internal static string ExchangeServerName = "exchangeName"; //not always needed 
     internal static string ReadAttachments = "0"; //1 means read attachments, 0 means dont 
     internal static string MailBoxEarliestDateToRead = "2011-01-05T00:00:00.000Z";//date of emails to read from 



     static void Main(string[] args) 
     { 
      //Connect to server 
      //ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); 
      ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); 
      //service.Credentials = new NetworkCredential("name", "pwd", "domain"); 
      service.Credentials = new NetworkCredential("dUser", "dPassword", "dDomain"); 

      //log in to mailbox 
      try 
      { 
       //service.Url = new Uri(serviceurl); 
       //Console.WriteLine(serviceurl); 
       //service.AutodiscoverUrl(MailBoxAliasName); 
       service.Url = new Uri("https://" + ExchangeServerName + "/EWS/" + MailBoxAliasName + "/inbox"); 
      } 
      catch (AutodiscoverRemoteException ex) 
      { 
       Console.WriteLine("Exception thrown: " + ex.Error.Message); 
       Console.ReadLine(); 
      } 


      //List folders 
      try 
      { 
       //Listing all the subfolders of the Inbox 
       FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(int.MaxValue)); 
       foreach (Item item in findResults) 
       { 
        Console.WriteLine(item.Subject); 
       } 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine("Exception thrown: " + ex.Message); 
       Console.ReadLine(); 
      } 


     } 
    } 
} 

回答

2

你確定你的服務器使用2007 SP1?此外,如果您不確定正確的網址,請嘗試使用自動發現功能,其中「[email protected]」是您網域上的實際電子郵件地址。

service.AutodiscoverUrl("[email protected]"); 

此外,您將您的網址設置爲等於URi。我認爲這不合法,它甚至編譯?

這裏是我作爲一個起點,當我實現了類似的東西了一些示例代碼 - codeproject.com

+0

它使用的Service Pack 2,但ExchangeVersion.Exchange2007_SP2想出了爲錯誤。我試着回到自動發現方法,我沒有使用它的原因是因爲它只是掛了一段時間。 – toosweetnitemare 2011-05-16 19:59:19

+0

也自動發現給我錯誤「自動發現服務找不到。」 – toosweetnitemare 2011-05-16 20:01:06

+0

查看我對URL/URi的新評論/問題。 – WEFX 2011-05-16 20:18:52