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 :
<dependency> <groupId>com.microsoft.ews-java-api</groupId> <artifactId>ews-java-api</artifactId> <version>2.0-SNAPSHOT</version> </dependency>
to connect
ExchangeService service = new ExchangeService(); ExchangeCredentials credentials = new WebCredentials("user@domain.local", "mypwd"); service.setCredentials(credentials); service.setUrl(new URI("https://myexchangemailserver.com/ews/Exchange.asmx"));
FolderView view = new FolderView(5); FindFoldersResults findResults = service.findFolders(WellKnownFolderName.PublicFoldersRoot, view); for (Folder item : findResults.getFolders()) { System.out.println(item.getDisplayName()); }
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); fs.close(); }
for (Item item : findResults3.getItems()) { System.out.println("** " + item.getSubject() + " " + item.getDateTimeSent()); item.delete(DeleteMode.HardDelete); }
service.close(); System.out.println("Done.");