Using Microsoft/Office 365 OAUTH + EWS


Microsoft Office365 EWS servers have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Microsoft Web OAuth instead of inputting user and password directly in application. This way is more secure, but a little bit complex.


Create your application in Azure Portal

To use Microsoft/Office365 OAUTH in your application, you must create a application in https://portal.azure.com.


Single tenant and multitenant in account type

When the register an application page appears, enter a meaningful application name and select the account type.

Select which accounts you would like your application to support.

Because we want to support all Office 365 and LIVE SDK (hotmail, outlook personal account), so select Accounts in any organizational directory and personal Microsoft accounts.


API Permission

Now we need to add permission to the application:

Click API Permission -> Add a permission -> Microsoft Graph -> Delegated Permission -> User.Read, email, offline_access, openid, profile, SMTP.Send, IMAP.AccessAsUser.All, POP.AccessAsUser.All.

EWS API permission

With the above permissions, your application can support SMTP, POP and IMAP service. If your application needs to support EWS protocol either, add EWS permission like this:

Click API Permission -> Add a permission -> APIs in my organization uses -> Office 365 Exchange Online -> Delegated Permission -> Check EWS.AccessAsUser.All

Here is permissions list:


Authentication and redirect uri


Client Id and client secrets

Now we need to create a client secret for the application, click Certificates and secrets -> client secrets and add a new client secret.

After client secret is created, store the client secret value to somewhere, Please store client secret value by yourself, because it is hidden when you view it at next time.


Branding and verify publisher

Now we click Branding, you can edit your company logo, URL and application name. If your application supports multitenant (access user in all Office 365 and Microsoft personal account), you must complete the publisher verification.

It is not difficult, you can have a look at publisher verification. After publisher verification is completed, your branding is like this:

You must complete the publisher verification for multitenant application, otherwise, your application will not request access token correctly.


Client id and tenant

Now you can click Overview to find your client id and tenant.

If your application is single tenant, use the tenant value in tokenUri and authUri instead of "common". If your application is multitenant, use "common" as tenant.

Above client_id and secret support both "Office365 + SMTP/POP/IMAP/EWS" and "Live (hotmail, outlook personal account) + SMTP/POP/IMAP".


Use client id and client secret to request access token

You can use client id and client secret to get the user email address and access token like this:


Access token expiration and refresh token

You don’t have to open browser to request access token every time. By default, access token expiration time is 3600 seconds, you can use the access token repeatedly before it is expired. After it is expired, you can use refresh token to refresh access token directly without opening browser. You can find full sample project in EAGetMail installation path to learn how to refresh token.

You should create your client id and client secret, don't use the client id in the sample project, it is only for test purpose. If you got "This app isn't verified" information, please click "advanced" -> Go to ... for test.

Example

[C# - Get access token and user with Microsoft.Identity.Client]
// You can install Microsoft.Identity.Client by NuGet
// Install-Package Microsoft.Identity.Client

using Microsoft.Identity.Client;

var pcaOptions = new PublicClientApplicationOptions
{
    ClientId = "your client id",
    TenantId = "common",
    RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient"
};

var pca = PublicClientApplicationBuilder
    .CreateWithApplicationOptions(pcaOptions)
    .WithLogging(MyLoggingMethod, LogLevel.Info,
           enablePiiLogging: true,
           enableDefaultPlatformLogging: true).
    Build();

var ewsScopes = new string[] { "https://outlook.office.com/EWS.AccessAsUser.All"};

// Make the interactive token request
var authResult = await pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync();

// then you can get access token and user from the following properties
// authResult.AccessToken;
// authResult.Account.Username;

Use access token to retrieve email from Office 365 EWS server

After you get user email address and access token, you can use the following codes to retrieving email using Office365 EWS XOAUTH2 mechanism.

Example

[Visual Basic, C#, C++] The following example demonstrates how to receive email with EAGetMail POP3 & IMAP Component, but it doesn't demonstrates the events and mail parsing usage. To get the full samples of EAGetMail, please refer to Samples section.

[VB - Retrieve email from Office 365 server using EWS OAUTH/XOAUTH2]
Imports System
Imports System.Globalization
Imports System.IO
Imports System.Text
Imports EAGetMail

Public Class TestClass
    ' Generate an unqiue email file name based on date time.
    Shared Function _generateFileName(ByVal sequence As Integer) As String
        Dim currentDateTime As DateTime = DateTime.Now
        Return String.Format("{0}-{1:000}-{2:000}.eml",
                            currentDateTime.ToString("yyyyMMddHHmmss", New CultureInfo("en-US")),
                            currentDateTime.Millisecond,
                            sequence)
    End Function
    
    Public Sub ReceiveMailByOauth(user As String, accessToken As String)

        Try
            ' Create a folder named "inbox" under current directory
            ' to save the email retrieved.
            Dim localInbox As String = String.Format("{0}\inbox", Directory.GetCurrentDirectory())

            ' If the folder is not existed, create it.
            If Not Directory.Exists(localInbox) Then
                Directory.CreateDirectory(localInbox)
            End If

            ' use SSL EWS + XOAUTH2
            Dim oServer As New MailServer("outlook.office365.com", user, accessToken, True,
                        ServerAuthType.AuthXOAUTH2, ServerProtocol.ExchangeEWS)

            Console.WriteLine("Connecting server ...")
            Dim oClient As New MailClient("TryIt")
            oClient.Connect(oServer)

            Console.WriteLine("Retrieving email list ...")
            Dim infos() As MailInfo = oClient.GetMailInfos()

            Console.WriteLine("Total {0} email(s)", infos.Length)

            For i As Integer = 0 To infos.Length - 1
                Console.WriteLine("Checking {0}/{1}", i + 1, infos.Length)
                Dim info As MailInfo = infos(i)

                ' Generate an unqiue email file name based on date time.
                Dim fileName As String = _generateFileName(i + 1)
                Dim fullPath As String = String.Format("{0}\{1}", localInbox, fileName)

                Console.WriteLine("Downloading {0}/{1}", i + 1, infos.Length)
                Dim oMail As Mail = oClient.GetMail(info)

                ' Save email to local disk
                oMail.SaveAs(fullPath, True)

                ' Mark email as deleted on server.
                Console.WriteLine("Deleting ... {0}/{1}", i + 1, infos.Length)
                oClient.Delete(info)
            Next

            Console.WriteLine("Disconnecting ...")
            ' Delete method just mark the email as deleted, 
            ' Quit method expunges deleted emails from server permanently.
            oClient.Quit()

            Console.WriteLine("Completed!")
        Catch ep As Exception
            Console.WriteLine("Error: {0}", ep.Message)
        End Try

    End Sub

End Class


[C# - Retrieve email from Office 365 server using EWS OAUTH/XOAUTH2] using System; using System.IO; using System.Globalization; using System.Text; using EAGetMail; class TestClass { // Generate an unqiue email file name based on date time static string _generateFileName(int sequence) { DateTime currentDateTime = DateTime.Now; return string.Format("{0}-{1:000}-{2:000}.eml", currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")), currentDateTime.Millisecond, sequence); } public void ReceiveMailByOauth(string user, string accessToken) { try { // Create a folder named "inbox" under current directory // to save the email retrieved. string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory()); // If the folder is not existed, create it. if (!Directory.Exists(localInbox)) { Directory.CreateDirectory(localInbox); } // use SSL EWS + XOAUTH2 MailServer oServer = new MailServer("outlook.office365.com", user, accessToken, true, ServerAuthType.AuthXOAUTH2, ServerProtocol.ExchangeEWS); Console.WriteLine("Connecting server ..."); MailClient oClient = new MailClient("TryIt"); oClient.Connect(oServer); Console.WriteLine("Retreiving email list ..."); MailInfo[] infos = oClient.GetMailInfos(); Console.WriteLine("Total {0} email(s)", infos.Length); for (int i = 0; i < infos.Length; i++) { Console.WriteLine("Checking {0}/{1} ...", i + 1, infos.Length); MailInfo info = infos[i]; // Generate an unqiue email file name based on date time. string fileName = _generateFileName(i + 1); string fullPath = string.Format("{0}\\{1}", localInbox, fileName); Console.WriteLine("Downloading {0}/{1} ...", i + 1, infos.Length); Mail oMail = oClient.GetMail(info); // Save mail to local file oMail.SaveAs(fullPath, true); // Mark the email as deleted on server. Console.WriteLine("Deleting ... {0}/{1}", i + 1, infos.Length); oClient.Delete(info); } Console.WriteLine("Disconnecting ..."); // Delete method just mark the email as deleted, // Quit method expunge the emails from server permanently. oClient.Quit(); Console.WriteLine("Completed!"); } catch (Exception ep) { Console.WriteLine("Error: {0}", ep.Message); } } }
[C++/CLI - Retrieve email from Office 365 server using EWS OAUTH/XOAUTH2] using namespace System; using namespace System::Globalization; using namespace System::IO; using namespace EAGetMail; //add EAGetMail namespace // Generate an unqiue email file name based on date time static String ^ _generateFileName(int sequence) { DateTime currentDateTime = DateTime::Now; return String::Format("{0}-{1:000}-{2:000}.eml", currentDateTime.ToString("yyyyMMddHHmmss", gcnew CultureInfo("en-US")), currentDateTime.Millisecond, sequence); } void ReceiveMailByOauth(String ^user, String ^accessToken) { try { // Create a folder named "inbox" under current directory // to save the email retrieved. String ^localInbox = String::Format("{0}\\inbox", Directory::GetCurrentDirectory()); // If the folder is not existed, create it. if (!Directory::Exists(localInbox)) { Directory::CreateDirectory(localInbox); } // use SSL EWS + XOAUTH2 MailServer ^oServer = gcnew MailServer("outlook.office365.com", user, accessToken, true, ServerAuthType::AuthXOAUTH2, ServerProtocol::ExchangeEWS); Console::WriteLine("Connecting server ..."); MailClient ^oClient = gcnew MailClient("TryIt"); oClient->Connect(oServer); Console::WriteLine("Retreiving email list ..."); array<MailInfo^>^infos = oClient->GetMailInfos(); Console::WriteLine("Total {0} email(s)", infos->Length); for (int i = 0; i < infos->Length; i++) { Console::WriteLine("Checking {0}/{1}", i + 1, infos->Length); MailInfo ^info = infos[i]; // Generate an unqiue email file name based on date time String^ fileName = _generateFileName(i + 1); String^ fullPath = String::Format("{0}\\{1}", localInbox, fileName); Console::WriteLine("Downloading {0}/{1}", i + 1, infos->Length); Mail ^oMail = oClient->GetMail(info); // Save email to local disk oMail->SaveAs(fullPath, true); // Mark email as deleted on server. Console::WriteLine("Deleting ... {0}/{1}", i + 1, infos->Length); oClient->Delete(info); } Console::WriteLine("Disconnecting ..."); // Delete method just mark the email as deleted, // Quit method expunge the emails from server permanently. oClient->Quit(); Console::WriteLine("Completed!"); } catch (Exception ^ep) { Console::WriteLine("Error: {0}", ep->Message); } }

Remarks

If you don't want to use OAUTH 2.0, Office 365 also supports traditional user authentication.

If your application is background service which doesn't support user interaction, please have a look at this topic: Use Office365 OAUTH in Background Service.

See Also

See Also

Using EAGetMail POP3 & IMAP4 .NET Component
User Authentication and SSL Connection
Enable TLS 1.2 on Windows XP/2003/2008/7/2008 R2
Using Gmail IMAP4 OAUTH
Using Gmail/GSuite Service Account + IMAP4 OAUTH
Using Office365 EWS OAUTH in Background Service
Using Hotmail IMAP4 OAUTH
Digital Signature and E-mail Encryption/Decryption
Unique Identifier (UIDL) in POP3 and IMAP4 protocol
Parse Bounced Email (delivery-report)
Work with winmail.dat (TNEF Parser)
EAGetMail Namespace References
EAGetMail POP3 & IMAP4 Component Samples

Online Tutorials

C# - Retrieve Email using Google/Gmail OAuth 2.0 Authentication + IMAP Protocol
C# -Retrieve Email using Gmail/G Suite OAuth 2.0 + IMAP4 Protocol in Background Service (Service Account)
C# -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + IMAP4 Protocol from Hotmail/Outlook Account
C# -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS/IMAP4 Protocol from Office 365 Account
C# -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS Protocol from Office 365 in Background Service

VB - Retrieve Email using Google/Gmail OAuth 2.0 Authentication + IMAP Protocol
VB -Retrieve Email using Gmail/G Suite OAuth 2.0 + IMAP4 Protocol in Background Service (Service Account)
VB -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + IMAP4 Protocol from Hotmail/Outlook Account
VB -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS/IMAP4 Protocol from Office 365 Account
VB -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS Protocol from Office 365 in Background Service

C++/CLR - Retrieve Email using Google/Gmail OAuth 2.0 Authentication + IMAP Protocol
C++/CLR -Retrieve Email using Gmail/G Suite OAuth 2.0 + IMAP4 Protocol in Background Service (Service Account)
C++/CLR -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + IMAP4 Protocol from Hotmail/Outlook Account
C++/CLR -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS/IMAP4 Protocol from Office 365 Account
C++/CLR -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS Protocol from Office 365 in Background Service