要点: 我需要使用EWS登录我的邮箱,但我一直收到440/401错误。
问题: 在我的代码中有什么明显的问题,为什么我一直得到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();
}
}
}
}
答案 0 :(得分:2)
您确定您的服务器使用的是2007 SP1吗?另外,如果您不确定网址是否正确,请尝试使用自动发现,其中“user@domain.com”是您网域上的实际电子邮件地址。
service.AutodiscoverUrl("user@domain.com");
此外,您将URL设置为等于URi。我不认为这是合法的;是甚至编译?
以下是我实施类似内容时使用的一些示例代码 - codeproject.com