Using Microsoft/Office 365 EWS OAUTH 2.0 in Background Service.


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.

You can click here to learn more detail about "OAUTH/XOAUTH2 with Office 365 EWS Service".

Office 365 OAuth 2.0 client credentials grant

Normal OAUTH requires user input user/password for authentication. Obviously, it is not suitable for background service. In this case, You can use the OAuth 2.0 client credentials grant, sometimes called two-legged OAuth, to access web-hosted resources by using the identity of an application. It only works for Office365 user, it doesn't work for personal Hotmail account.


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 just need to support Offic365 user in our organization, so select Accounts in this organizational directory only (single tenant).

Do not select supporting Microsoft personal account, because there is no way to access Microsoft personal account in background service.


API Permission

Click API Permission -> Microsoft Graph -> Delegated Permission -> User.Read. Click API Permission -> Add a permission -> APIs in my organization uses -> Office 365 Exchange Online -> Application Permission -> Other permission -> full_access_as_app

If your current user is not a user in a verified domain or Offic 365, you will not find Office 365 Exchange Online in API list, then you have to add this API permission manually.

{
    "resourceAppId": "00000002-0000-0ff1-ce00-000000000000",
    "resourceAccess": [
        {
            "id": "dc890d15-9560-4a4c-9b7f-a736ec74ec40",
            "type": "Role"
        }
    ]
}
    


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.


Grant admin consent

To use your application to access user mailbox in Office365 domain, you should get admin consent by Office365 domain administrator.

After administrator authorized the permissions, you can use your application to access any users mailbox in Office365 domain.


Use EWS OAUTH 2.0 to retrieve email by impersonating user in Office365 domain

The following examples demonstrate how to retrieve email with EWS OAUTH

Example

[C# - Retrieve email by impersonating user in Office365]

using System;
using System.Text;
using System.Net;
using System.IO;
using EAGetMail;

class TestClass
{
    static string _postString(string uri, string requestData)
    {
        HttpWebRequest httpRequest = WebRequest.Create(uri) as HttpWebRequest;
        httpRequest.Method = "POST";
        httpRequest.ContentType = "application/x-www-form-urlencoded";

        using (Stream requestStream = httpRequest.GetRequestStream())
        {
            byte[] requestBuffer = Encoding.UTF8.GetBytes(requestData);
            requestStream.Write(requestBuffer, 0, requestBuffer.Length);
            requestStream.Close();
        }

        try
        {
            HttpWebResponse httpResponse = httpRequest.GetResponse() as HttpWebResponse;
            var responseText = new StreamReader(httpResponse.GetResponseStream()).ReadToEnd();
            Console.WriteLine(responseText);
            return responseText;
        }
        catch (WebException ep)
        {
            if(ep.Status == WebExceptionStatus.ProtocolError)
            { 
                var responseText = new StreamReader(ep.Response.GetResponseStream()).ReadToEnd();
                Console.WriteLine(responseText);
            }

            throw ep;
        }
    }

    // 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()
    {
        try
        {
            string client_id = "8f54719b-4070-41ae-91ad-f48e3c793c5f";
            string client_secret = "cbmYyGQjz[d29wL2ArcgoO7HLwJXL/-.";

         // If your application is not created by Office365 administrator, 
         // please use Office365 directory tenant id, you should ask Offic365 administrator to send it to you.
         // Office365 administrator can query tenant id in https://portal.azure.com/ - Azure Active Directory.
            string tenant = "79a42c6f-5a9a-439b-a2ca-7aa1b0ed9776";

            string requestData = 
                string.Format("client_id={0}&client_secret={1}&scope=https://outlook.office365.com/.default&grant_type=client_credentials",
                    client_id, client_secret);

            string tokenUri = string.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", tenant);
            string responseText = _postString(tokenUri, requestData);

            OAuthResponseParser parser = new OAuthResponseParser();
            parser.Load(responseText);

            // 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);
            }

            string officeUser = "user@mydomain.onmicrosoft.com";

            // use SSL EWS + OAUTH 2.0
            MailServer oServer = new MailServer("outlook.office365.com", officeUser, parser.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);
        }
    }
}


[VB - Retrieve email by impersonating user in Office365] Imports System Imports System.Text Imports System.Net Imports EAGetMail Public Class TestClass Function _postString(ByVal uri As String, ByVal requestData As String) As String Dim httpRequest As HttpWebRequest = TryCast(WebRequest.Create(uri), HttpWebRequest) httpRequest.Method = "POST" httpRequest.ContentType = "application/x-www-form-urlencoded" Using requestStream As Stream = httpRequest.GetRequestStream() Dim requestBuffer As Byte() = Encoding.UTF8.GetBytes(requestData) requestStream.Write(requestBuffer, 0, requestBuffer.Length) requestStream.Close() End Using Try Dim httpResponse As HttpWebResponse = TryCast(httpRequest.GetResponse(), HttpWebResponse) Dim responseText = New StreamReader(httpResponse.GetResponseStream()).ReadToEnd() Console.WriteLine(responseText) Return responseText Catch ep As WebException If ep.Status = WebExceptionStatus.ProtocolError Then Dim responseText = New StreamReader(ep.Response.GetResponseStream()).ReadToEnd() Console.WriteLine(responseText) End If Throw ep End Try End Function ' 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() Try Dim client_id As String = "8f54719b-4070-41ae-91ad-f48e3c793c5f" Dim client_secret As String = "cbmYyGQjz[d29wL2ArcgoO7HLwJXL/-." ' If your application is not created by Office365 administrator, ' please use Office365 directory tenant id, you should ask Offic365 administrator to send it to you. ' Office365 administrator can query tenant id in https://portal.azure.com/ - Azure Active Directory. Dim tenant As String = "79a42c6f-5a9a-439b-a2ca-7aa1b0ed9776" Dim requestData As String = String.Format("client_id={0}&client_secret={1}&scope=https://outlook.office365.com/.default&grant_type=client_credentials", client_id, client_secret) Dim tokenUri As String = String.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", tenant) Dim responseText As String = _postString(tokenUri, requestData) Dim parser As OAuthResponseParser = New OAuthResponseParser() parser.Load(responseText) Dim officeUser As String = "user@mydomain.onmicrosoft.com" ' 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", officeUser, parser.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 expunge the 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

Remarks

You don't have to request access token every time, once you get an access token, it is valid within 3600 seconds.

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

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
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