Search code examples
javaexchangewebservices

"Mailbox does not exist." when fetching emails on EWS


I am trying to access emails on a Office365 mailbox, using Exchange Web Services (EWS).

My O365 admin has created :

  • the shared mailbox : shared@domain.com
  • the account : my.account@domain.com
  • a group, giving access to the account on the mailbox

I am able to retrieve the Oauth token using the appId/tenantId and a UserNamePasswordParameters using the account's credentials, and now I am trying to retrieve the emails from the mailbox, but I get this error :

microsoft.exchange.webservices.data.core.exception.service.remote.ServiceResponseException: Mailbox does not exist.

here's my code :

  public Iterable fetchEmails(String token, String account) throws Exception {

    if(token==null) {
      token = getToken();
    }

    FindItemsResults<Item> emails;

    try (ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2)) {

      service.getHttpHeaders().put("Authorization", "Bearer " + token);
      service.setUrl(new URI("https://outlook.office365.com/EWS/Exchange.asmx"));
      service.setWebProxy(new WebProxy(PROXY_HOST, PROXY_PORT));

      FolderId folder = new FolderId(WellKnownFolderName.Inbox, new Mailbox(account));

      emails = service.findItems(folder, new ItemView(15));
    }

    return emails;
  }

Solution

  • OK, it was a bit stupid.. I got confused because the account is also an email..

    solution is to pass the mailbox (shared@domain.com) instead of the account (my.account@domain.com) when building the Mailbox object :

    FolderId folder = new FolderId(WellKnownFolderName.Inbox, new Mailbox("shared@domain.com"));
    

    And now it's working, I am able to get the emails.