Follow @abushalihu Abu The Geek: October 2011

Thursday, October 13, 2011

Microsoft Exchange Connector - Exchange Web Services (EWS) API in Java

     Hi! Friends... After a long gap I would like to share an useful Java API called EWS.
Exchange Web Services (EWS) is an open source Java API written by Microsoft. This API provides developers programmatic access to Microsoft Exchange Servers (Versions 2007 and above) through Java. The latest version is 1.1.5. By using the API you can send, receive emails. To use this API in your Java program you have to download and install the below third party libraries. In the given version 1.1.5 there was an issue with handling of Control Characters. That API failed to handle the Control Character's. I found that issue when i receive an email which contains Control Characters from MS Exchange Server 2010. I have upgraded this API to 1.1.5.1 in which i have removed all the Control Characters.

Pre-requisites

Download and install the Java SDK

The below required libraries included in the lib directory.

Apache Commons HttpClient 3.1
Apache Commons Codec 1.4
Apache Commons Logging 1.1.1
JCIFS 1.3.15

Accessing EWS by using the EWS Java API
ExchangeService service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials("emailId@domain.com", "password");
service.setCredentials(credentials);
To set the Exchange webservice URL
String uri = https://hostName/ews/Exchange.asmx;
URI uriObj = new URI(uri);
service.setUrl(uriObj);

Here hostName is your exchange server's domain name. (eg. mail.microsoft.com)

To set the Exchange webservice URL by Autodiscover
service.autodiscoverUrl("<your e-mail address>");
The autodiscoverurl method takes your emailId as argument and it automatically fetches the exchange webservice's nearest endpoint.
You have to set your endpoint URL by manually or using autodiscovery but not both!.

Sample Program to receive unread emails in inbox from MS Exchange Server:

import java.net.URI;
import java.util.Iterator;
import microsoft.exchange.webservices.data.ConflictResolutionMode;
import microsoft.exchange.webservices.data.EmailMessage;
import microsoft.exchange.webservices.data.EmailMessageSchema;
import microsoft.exchange.webservices.data.ExchangeCredentials;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.FindItemsResults;
import microsoft.exchange.webservices.data.Item;
import microsoft.exchange.webservices.data.ItemId;
import microsoft.exchange.webservices.data.ItemSchema;
import microsoft.exchange.webservices.data.ItemView;
import microsoft.exchange.webservices.data.SearchFilter;
import microsoft.exchange.webservices.data.SortDirection;
import microsoft.exchange.webservices.data.WebCredentials;
import microsoft.exchange.webservices.data.WellKnownFolderName;

class EWSReadEmail {
public static void main(String args[]) throws Exception {
    ExchangeService service = new ExchangeService();
    ExchangeCredentials credentials = new WebCredentials("emailId@domain.com", "password");
    service.setCredentials(credentials);
    URI uri = new URI("https://yourhostname/ews/Exchange.asmx");
    service.setUrl(uri);
    ItemView view = new ItemView(100);    //Read maximum of 100 emails
    view.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Ascending);    // Read emails by received date order by Ascending
    FindItemsResults < Item > results = service.findItems(WellKnownFolderName.Inbox, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false), view);    //Read only unread emails in inbox
    Iterator<Item> itr = results.iterator();
    System.out.println("Total Unread Emails="+ results.getTotalCount());
    while(itr.hasNext()) {
        Item item = itr.next();
        ItemId itemId = item.getId();
        EmailMessage email = EmailMessage.bind(service, itemId);
        System.out.println("Sender= " + email.getSender());
        System.out.println("Subject= " + email.getSubject());
        System.out.println("Body= " + email.getBody());
        email.setIsRead(true);        //Set the email to read.
        email.update(ConflictResolutionMode.AlwaysOverwrite);
    }
    }
}
You can download the source and binaries here