Search code examples
javadirectoryexchangewebservices

Read MSExchange emails from a custom folder


Is there a way to read emails from a custom folder in MS-Exchange using Java? I'm able to read from the Inbox, but I have custom folder names where the emails are moved to that I'd like to have the code read in those folders.

Below is my current code to read from Inbox:

ExchangeCredentials credentials = new WebCredentials("userName", "passWORD", "domain");
service.setCredentials(credentials);
service.setUrl(new URI("https://outlook.mycompany.com/ews/exchange.asmx"));

ItemView view = new ItemView(200);

FindItemsResults<Item> findResults = service.findItems(WellKnownFolderName.Inbox , view);

Instead I want something like this:

FindItemsResults<Item> findResults = service.findItems("My Custom Folder" , view);

I've tried with this, but it didn't work:

FindItemsResults<Item> findResults = service.findItems(FolderId.getFolderIdFromString("My Custom Folder") , view);

Solution

  • You need to use the FindFolder operation to find the ewsId of the Folder in question. Generally the easy way to do this is turn the folder you want to access into a Path eg if the folder is a subfolder of the Inbox then the Path string would be \Inbox\Subfolder name then you should be able to use something like the following to split the path out do multiple finds to get the specific folder your after (this is c# but you should be able to convert to java easily as the class are mostly the same)

        internal static Folder GetFolderFromPath(ExchangeService service,String MailboxName,String FolderPath)
        {
            FolderId folderid = new  FolderId(WellKnownFolderName.MsgFolderRoot,MailboxName);   
            Folder tfTargetFolder = Folder.Bind(service,folderid);
            PropertySet psPropset = new PropertySet(BasePropertySet.FirstClassProperties);
            String[] fldArray = FolderPath.Split('\\'); 
            for (Int32 lint = 1; lint < fldArray.Length; lint++) { 
                FolderView fvFolderView = new FolderView(1);
                fvFolderView.PropertySet = psPropset;
                SearchFilter  SfSearchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName,fldArray[lint]); 
                FindFoldersResults findFolderResults = service.FindFolders(tfTargetFolder.Id,SfSearchFilter,fvFolderView); 
                if (findFolderResults.TotalCount > 0){ 
                foreach(Folder folder in findFolderResults.Folders){ 
                    tfTargetFolder = folder;                
                    } 
                } 
                else{ 
                    tfTargetFolder = null;  
                    break;  
                }     
            }
            if (tfTargetFolder != null)
            {
                return tfTargetFolder;
            }
            else
            {
                throw new Exception("Folder Not found");
            }
        }
    

    Cheers Glen