Rekcs
Rekcs

Reputation: 879

Error The remote server returned an error: (401) Unauthorized

I am trying to get emails from my shared outlook exchange inbox, but unfortunately it is not working because of this error:

The request failed. The remote server returned an error: (401) Unauthorized

This is the code I am currently using. It is preety simple:

static void Main(string[] args)
{
    ExchangeService exchange = new ExchangeService();
    try
    {
        Console.WriteLine("Registering Exchange connection");

        exchange.Credentials = new WebCredentials("user", "password", "domain");
    }
    catch
    {
        Console.WriteLine("new ExchangeService failed. Press enter to exit:");
        return;
    }

    exchange.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");

    try
    {
        Console.WriteLine("Reading mail");

        // Read 100 mails
        foreach (EmailMessage email in exchange.FindItems(WellKnownFolderName.Inbox, new ItemView(100)))
        {
            Console.WriteLine(email);

        }

        Console.WriteLine("Exiting");
    }
    catch (Exception e)
    {
        Console.WriteLine("An error has occured. \n:" + e.Message);
    }
}

Upvotes: 2

Views: 18403

Answers (1)

Glen Scales
Glen Scales

Reputation: 22032

Basic authentication in now disabled by default in Office365 so you should avoid using it. Look at implementing oAuth in your see code https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth

If your writing a new application you may also want to consider using the Graph API rather the EWS (which is for legacy ,OnPrem or Migration apps) if all the mailboxes you need to access are in the Cloud.

Upvotes: 2

Related Questions