今天实验了一下使用EWS访问exchange邮件,网上说的都很简单,可我却是碰到了N多问题啊,不过最终还是成功了,也不枉我加班了。把一些方法及遇到的问题记录下来,希望对有类似exchange功能开发需求的人有所帮助。
第一步是下载Exchange Web Services Managed API,这个DLL封装了很多对EWS的访问,比起直接使用EWS生成的代理类,那是方便多了,下载地址:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c3342fb3-fbcc-4127-becf-872c746840e1
使用EWS的代码示例网上有不少,微软站点上也有,博客园里有两篇关于这个的介绍(下篇未给出链接):
http://www.cnblogs.com/diaojia/archive/2010/10/19/1855839.html
代码还是比较简单的,在此我贴上我的测试代码:
public class AccessInfo
{
public string UserName;
public string Password;
public string Domain;
public string ServerUrl;
public string Email;
}
class Program
{
static void Main(string[] args)
{
AccessInfo info = new AccessInfo()
{
UserName = "administrator",
Password = "p@ssw0rd",
Domain = "contoso.com",
ServerUrl = "https://contoso-exchange.contoso.com/ews/Exchange.asmx Email = "administrator@contoso.com"
};
ReadMail(info);
Console.Read();
}
static void ReadMail(AccessInfo Info)
{
//ExchangeService版本为2010
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
//参数是用户名,密码,域
service.Credentials = new WebCredentials(Info.UserName, Info.Password, Info.Domain);
//给出Exchange Server的URL http://xxxxxxx
service.Url = new Uri(Info.ServerUrl);
//你自己的邮件地址 xxx@xxx.xxx
//service.AutodiscoverUrl(Info.Email);
//创建过滤器, 条件为邮件未读.
SearchFilter sf = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
//查找Inbox,加入过滤器条件,结果10条
FindItemsResults<Item> findResults = null;
try
{
findResults = service.FindItems(WellKnownFolderName.Inbox, sf, new ItemView(10));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
foreach (Item item in findResults.Items)
{
EmailMessage email = EmailMessage.Bind(service, item.Id);
Console.WriteLine(email.Subject);
}
}
}",
这段代码是最终测试成功的代码,下面列一下碰到过的问题。
1、在service.AutodiscoverUrl(Info.Email)处出现异常:AutodiscoverUrl could not be located
这个问题最终没有得到根本解决,我只是简单的把这一行注释了,因为我想既然显示的指定了service.Url,那也就没必要autodiscover了;
2、在service.FindItems(WellKnownFolderName.Inbox, sf, new ItemView(10))处出现异常,提示Http404错误
这个问题郁闷了很久,因为写的URL明明是没有错的,在浏览器中都可以访问,也可以使用它来生成代理类,后面将要放弃的时候,找到了跟我有同样遭遇的人写
的帖子:http://www.cnblogs.com/Bear-Study-Hard/archive/2010/10/11/1847824.html。(又是博客园),里头说到是因为EWS站点禁用了SSL的缘故。的确
我的EWS站点也是禁用了SSL的,我比较不喜欢在浏览器里访问时老提示证书无效的警告。于是乎把SSL加上了,同时把http改为https(一开始测试是写的http)。