Share this page 

Handle MS Exchange public foldersTag(s): Networking

You can access the public folders from Microsoft Exchange by calling the Exchange Web Services (EWS). An Open Source library is available to allow Java program to easily call thoses services, ews-java-api. You can get a ready to use jar at the Sonatype OSS repository. Be sure to get all the dependencies! With Maven, use this POM :






to connect

  ExchangeService service = new ExchangeService();

  ExchangeCredentials credentials = new WebCredentials("user@domain.local", "mypwd");


  service.setUrl(new URI(""));

to retrieve the first 5 public folders from the root

  FolderView view = new FolderView(5);

  FindFoldersResults findResults = service.findFolders(WellKnownFolderName.PublicFoldersRoot, view);

  for (Folder item : findResults.getFolders()) {



to navigate, you position yourself level by level. You can save each item of a folder as EML file. EML is the format used by Exchange and can be opened by Outlook or any mail client and be parsed by JavaMail .

For example, we want to go in the folder \level1\level2, then save the first 5 items as EML files.

  // search for a specific folder and then list the first 5 item

  FolderView view = new FolderView(10);

  SearchFilter filter = new SearchFilter.ContainsSubstring(FolderSchema.DisplayName, "level1");

  FindFoldersResults findResults = service.findFolders(WellKnownFolderName.PublicFoldersRoot, filter, view);

  // for (Folder item : findResults.getFolders()) {

  //      System.out.println("* " + item.getDisplayName());

  // }

  SearchFilter filter2 = new SearchFilter.ContainsSubstring(FolderSchema.DisplayName, "level2");

  FindFoldersResults findResults2 = findResults.getFolders().get(0).findFolders(filter2, view);

  ItemView view2 = new ItemView(5);

  FindItemsResults<Item> findResults3 = findResults2.getFolders().get(0).findItems(view2);

  // save .eml

  for (Item item : findResults3.getItems()) {

        System.out.println("!! " + item.getSubject());

        String subject = item.getSubject();

        item.load(new PropertySet(ItemSchema.MimeContent));

        MimeContent mc = item.getMimeContent();

        // it may be a good idea to sanitize a little bit the filename to remove illegal characters

        // see this HowTo

        FileOutputStream fs = new FileOutputStream("c:/temp/" + subject + ".eml");

        byte b[] = mc.getContent();

        fs.write(b, 0, b.length);



to delete

  for (Item item : findResults3.getItems()) {

        System.out.println("** " + item.getSubject() + " " + item.getDateTimeSent());



when done, don't forget to close your connection!



In this HowTo, EWS was used to access the public folders but you can use it to send/receive regular mail or create appointment/task. See for more details.