'C#: How to read Microsoft office emails. Different approaches

I need to read emails using C# (concrete task - count of received/sent emails by range). Ideally, user enters credentials of his Microsoft Office/Exchange email on webpage and receive this info.

I see the following ways to implement it.

  1. ExchangeService

using nuget package Microsoft.Exchange.WebServices we can get access to email profile, e.g.

    ExchangeService _service;

        _service = new ExchangeService(ExchangeVersion.Exchange2013_SP1)
        {
            Credentials = new WebCredentials("[email protected]", "mypassword"),
        };
        _service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
        _service.TraceEnabled = true;
        _service.TraceFlags = TraceFlags.All;

        var items = _service.FindItems(WellKnownFolderName.Inbox, searchFilter: new SearchFilter.IsGreaterThan(TaskSchema.DateTimeCreated, DateTime.Now.AddDays(-10)), new ItemView(int.MaxValue));

sometimes this approach works, but for some cases does not work (for example, if 2-way authentication is enabled)

  1. using IAuthenticationProvider and Active Directory Tenant Id

there is a way to impement own IAuthenticationProvider with implementation AuthenticateRequestAsync like this

    public async Task AuthenticateRequestAsync(HttpRequestMessage request)
    {
        var token = await GetTokenAsync();

        request.Headers.Authorization = new AuthenticationHeaderValue(token.TokenType, token.AccessToken);
    }

after this we can create GraphServiceClient like this:

        GraphServiceClient graphServiceClient =
            new GraphServiceClient(_authenticationProvider, _graphHttpProvider);

and can send email, for example:

            await graphServiceClient.Users[fromAddress]
                .SendMail(message, false)
                .Request()
                .PostAsync();

I suppose, similar way I can get access to folders also

For this approach, I assume, I need to get tenantId etc (I'm a little confused with it)

How to implement stable solution to read Microsoft Office/Exchange emails ?



Solution 1:[1]

I would avoid the first approach EWS is now legacy and in that example your using Basic Authentication which is depreciated and will be disabled in October this year (if it hasn't already been).

For 2 you need to create a Azure Application registration see https://docs.microsoft.com/en-us/graph/use-the-api which has some detailed documentation and walkthroughs on how to do that. There's also https://docs.microsoft.com/en-us/graph/tutorials/aspnet-core which is a pretty good example of building a webapp that takes you through all the steps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Glen Scales