我正在尝试制作一个程序,它将整齐地打印我收件箱的所有邮件正文,但交换Web服务使其变得困难。我似乎可以轻松访问除消息正文之外的所有内容。这就是我现在正在做的事情
static final int SIZE = 10;
public static void main(String [] args) throws Exception {
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
ExchangeCredentials credentials = new WebCredentials("USERNAME","PASS");
service.setCredentials(credentials);
service.setUrl(new URI("https://MY_DOMAIN/ews/exchange.asmx"));
ItemView view = new ItemView (SIZE);
FindItemsResults<Item> findResults = service.findItems(WellKnownFolderName.Inbox, view);
System.out.println(findResults.getItems().size() + "Messages");
for (int i = 0; i < SIZE; ++i) {
try {
Item item = findResults.getItems().get(i);
System.out.println("SUBJECT: " + item.getSubject());
System.out.println("TO: " + item.getDisplayTo());
System.out.println("BODY: " + item.getBody().toString());
} catch (IndexOutOfBoundsException e) {
break;
}
}
当然,我的代码填写了我的凭据和域名。当我运行这个时,我收到了这条消息。
Exception in thread "main" microsoft.exchange.webservices.data.ServiceObjectPropertyException: You must load or assign this property before you can read its value.
at microsoft.exchange.webservices.data.PropertyBag.getPropertyValueOrException(Unknown Source)
at microsoft.exchange.webservices.data.PropertyBag.getObjectFromPropertyDefinition(Unknown Source)
at microsoft.exchange.webservices.data.Item.getBody(Unknown Source)
at Main.main(Main.java:26)
第26行是我尝试打印身体的行。我做错了什么?
答案 0 :(得分:2)
FindItem操作不会返回消息正文,因此您需要向服务器发出单独的GetItem请求以获取此消息。在Managed API中,您应该能够使用Load方法执行此操作,只需更改
即可Item item = findResults.getItems().get(i);
item.Load()
干杯 格伦
答案 1 :(得分:1)
我实际上已经弄明白了。看起来ExchangeService将在完成拉动所需信息后关闭连接。解决这个问题我做了一个功能
private static ExchangeService getService() throws Exception {
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
ExchangeCredentials credentials = new WebCredentials("USERNAME","PASS");
service.setCredentials(credentials);
service.setUrl(new URI("DOMAIN"));
return service;
}
然后我就这样调用load
getService().loadPropertiesForItems(findResults, itempropertyset);
我将itempropertyset定义为
PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
itempropertyset.setRequestedBodyType(BodyType.Text);
view.setPropertySet(itempropertyset);