Search code examples
javaemailexchangewebservicesewsjavaapi

Printing the body of a message


I am trying to make a program that will neatly print all the bodies of the messages of my inbox yet exchange web services is making it difficult. I seem to have easy access to everything except the body of the message. This is what I'm doing right now

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;
    }


}

Of course, I have my credentials and domain filled out fittingly for my code. When I run this I get this message though.

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)

Line 26 is the line where I try to print the body. What am I doing wrong?


Solution

  • I've figured it out actually. It looks like ExchangeService will close the connection after it is done pulling the needed info. to fix this I made a function

    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;
    }
    

    I then call load like so

    getService().loadPropertiesForItems(findResults, itempropertyset);
    

    Where I define itempropertyset as such

    PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
    itempropertyset.setRequestedBodyType(BodyType.Text);
    view.setPropertySet(itempropertyset);