Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting 403 error when trying to get Folder items from Office 365 mailbox using ExchangeService

I'm trying to read all Inbox email items from an Office 365 mailbox using ExchangeService.

For that, I:

  • Created an app in my AzureAD portal.
  • Given this app all permissions.
  • Issues this app an access secret to use in my code.

The code works to the point that I sucessfully get a token, but when trying to get the folder items I get an 403 error:

'The request failed. The remote server returned an error: (403) Forbidden.'

I get this error from my dev and my prod environments so I'm pretty sure it's not a network or port issue.

Here's my code:

var cca = ConfidentialClientApplicationBuilder
            .Create("myApplicationId")
            .WithClientSecret("myClientSecret")
            .WithTenantId("myTenantId")
            .Build();

var ewsScopes = new string[] { "https://outlook.office365.com/.default" };

// This is where I get the token   
var authResult = await cca.AcquireTokenForClient(ewsScopes).ExecuteAsync();

var ewsClient = new ExchangeService();

ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
ewsClient.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "[email protected]");

ewsClient.HttpHeaders.Add("X-AnchorMailbox", "[email protected]");

// This is where I get the 403 error:
var items = ewsClient.FindItems(
     new FolderId(WellKnownFolderName.Inbox, new Mailbox("[email protected]")),
     new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter[] {}
     ),
     new ItemView(15)
);
like image 376
Koby Douek Avatar asked Oct 29 '25 07:10

Koby Douek


1 Answers

403 if its coming back from Office365 sounds like they have either disabled EWS on the Mailbox your trying to access or they have limited the clients that are allowed to connect eg https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-control-access-to-ews-in-exchange . You could try testing EWS itself using a user account via the EWSeditor https://github.com/dseph/EwsEditor

like image 168
Glen Scales Avatar answered Oct 31 '25 22:10

Glen Scales