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

[VB6 - Use EWS OAUTH 2.0 to retrieve email by impersonating user in Offic365]

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Const MailServerAuthLogin = 0
Const MailServerAuthCRAM5 = 1
Const MailServerAuthNTLM = 2
Const MailServerAuthXOAUTH2 = 3

Const CRYPT_MACHINE_KEYSET = 32 
Const CRYPT_USER_KEYSET = 4096 

Private Function GenerateRequestData() 

    Const client_id = "8f54719b-4070-41ae-91ad-f48e3c793c5f"
    Const client_secret = "cbmYyGQjz[d29wL2ArcgoO7HLwJXL/-."
    Const scope = "https://outlook.office365.com/.default"

    GenerateRequestData = "client_id=" & client_id & "&client_secret=" & client_secret & "&scope=" & scope & "&grant_type=client_credentials"

End Function

Private Function RequestAccessToken(requestData)
    RequestAccessToken = ""

    If requestData = "" Then
        Exit Function
    End If

On Error GoTo ErrorHandle

    Dim httpRequest
    Set httpRequest = CreateObject("MSXML2.ServerXMLHTTP")
    
    ' 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.
    Const tenant_id =  "79a42c6f-5a9a-439b-a2ca-7aa1b0ed9776"
    
    Dim tokenUri 
    tokenUri = "https://login.microsoftonline.com/" & tenant_id & "/oauth2/v2.0/token"
    
    httpRequest.setOption 2, 13056
    httpRequest.Open "POST", tokenUri, True
    httpRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    httpRequest.Send requestData
    
    Do While httpRequest.ReadyState <> 4
        DoEvents
        httpRequest.waitForResponse (1)
    Loop
    
    Dim Status
    Status = httpRequest.Status
    
    If Status < 200 Or Status >= 300 Then
        MsgBox "Failed to get access token from server."
        MsgBox httpRequest.responseText
        Exit Function
    End If

    Dim result
    result = httpRequest.responseText
    
    Dim oauthParser As New EASendMailObjLib.OAuthResponseParser
    oauthParser.Load result
    
    Dim accessToken
    accessToken = oauthParser.AccessToken
    
    If accessToken = "" Then
        MsgBox "Failed to parse access token from server response."
        Exit Function
    End If

    RequestAccessToken = accessToken
    Exit Function

ErrorHandle:
    MsgBox "Failed to request access token." & Err.Description
        
End Function

Public Sub ReceiveMail()
    
On Error GoTo ErrorHandle
    ' Office365User is the full email address of the user in Offic365
    Dim Office365User
    Office365User = "user@mydomain.onmicrosoft.com"

    Dim accessToken As String
    ' request access token from MS server
    ' withou user interaction
    accessToken = RequestAccessToken(GenerateRequestData())

    If accessToken = "" Then
        Exit Sub
    End If

    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"
    
    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "outlook.office365.com"

    oServer.User = Office365User
    oServer.Password = accessToken

    oServer.AuthType = MailServerAuthXOAUTH2
    
    oServer.Protocol = MailServerEWS
    oServer.SSLConnection = True


    oClient.Connect oServer

    Dim infos
    Set infos = oClient.GetMailInfoList()
    
    Dim i
    For i = 0 To infos.Count - 1
        Dim info
        Set info = infos.Item(i)
        
        MsgBox "UIDL: " & info.UIDL
        MsgBox "Index: " & info.Index
        MsgBox "Size: " & info.Size

        MsgBox "Read: " & info.Read
        MsgBox "Deleted: " & info.Deleted
                    
        Dim oMail
        Set oMail = oClient.GetMail(info)
        'Save mail to local
        oMail.SaveAs "d:\tempfolder\" & i & ".eml", True

        ' Delete email from server
        oClient.Delete info
    Next

    oClient.Quit
    Exit Sub

ErrorHandle:
    ''Error handle
    MsgBox Err.Description
    
    oClient.Close
End Sub


[Visual C++ - Use EWS OAUTH 2.0 to retrieve email by impersonating user in Offic365] #include "stdafx.h" #include <tchar.h> #include <Windows.h> #include "eagetmailobj.tlh" using namespace EAGetMailObjLib; #include "msxml3.tlh" using namespace MSXML2; const int MailServerPop3 = 0; const int MailServerImap4 = 1; const int MailServerEWS = 2; const int MailServerDAV = 3; const int MailServerMsGraph = 4; const int MailServerAuthLogin = 0; const int MailServerAuthCRAM5 = 1; const int MailServerAuthNTLM = 2; const int MailServerAuthXOAUTH2 = 3; BOOL RequestAccessToken(const TCHAR* requestData, _bstr_t &accessToken) { try { IServerXMLHTTPRequestPtr httpRequest = NULL; httpRequest.CreateInstance(__uuidof(MSXML2::ServerXMLHTTP)); if (httpRequest == NULL) { _tprintf(_T("Failed to create XML HTTP Object, please make sure you install MSXML 3.0 on your machine.\r\n")); return FALSE; } _bstr_t fullRequest = requestData; const char* postData = (const char*)fullRequest; LONG cdata = strlen(postData); LPSAFEARRAY psaHunk = ::SafeArrayCreateVectorEx(VT_UI1, 0, cdata, NULL); for (LONG k = 0; k < (int)cdata; k++) { BYTE ch = (BYTE)postData[k]; ::SafeArrayPutElement(psaHunk, &k, &ch); } _variant_t requestBuffer; requestBuffer.vt = (VT_ARRAY | VT_UI1); requestBuffer.parray = psaHunk; // 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. const TCHAR* tenant_id = _T("79a42c6f-5a9a-439b-a2ca-7aa1b0ed9776"); _variant_t async(true); _bstr_t tokenUri(_T("https://login.microsoftonline.com/")); tokenUri += tenant_id; tokenUri += _T("/oauth2/v2.0/token"); httpRequest->setOption((MSXML2::SERVERXMLHTTP_OPTION)2, 13056); httpRequest->open(L"POST", tokenUri, async, vtMissing, vtMissing); httpRequest->setRequestHeader(L"Content-Type", L"application/x-www-form-urlencoded"); httpRequest->send(requestBuffer); while (httpRequest->readyState != 4) { httpRequest->waitForResponse(1); } long status = httpRequest->status; _bstr_t responseText = httpRequest->responseText; if (status < 200 || status >= 300) { _tprintf(_T("Failed to get access token from server: %d %s\r\n"), status, (const TCHAR*)responseText); return FALSE; } IOAuthResponseParserPtr oauthParser = NULL; oauthParser.CreateInstance(__uuidof(EASendMailObjLib::OAuthResponseParser)); oauthParser->Load(responseText); accessToken = oauthParser->AccessToken; if (accessToken.length() == 0) { _tprintf(_T("Failed to parse access token from server response: %d %s\r\n"), status, (const TCHAR*)responseText); return FALSE; } return TRUE; } catch (_com_error &ep) { _tprintf(_T("Failed to get access token: %s"), (const TCHAR*)ep.Description()); return FALSE; } } _bstr_t GenerateRequestData() { const TCHAR* client_id = _T("8f54719b-4070-41ae-91ad-f48e3c793c5f"); const TCHAR* client_secret = _T("cbmYyGQjz[d29wL2ArcgoO7HLwJXL/-."); const TCHAR* scope = _T("https://outlook.office365.com/.default"); _bstr_t buffer = _T("client_id="); buffer += client_id; buffer += _T("&client_secret="); buffer += client_secret; buffer += _T("&scope="); buffer += scope; buffer += _T("&grant_type=client_credentials"); return buffer; } void ReceiveMail() { ::CoInitialize(NULL); try { _bstr_t accessToken; // request access token from MS server without user interaction if (!RequestAccessToken((const TCHAR*)GenerateRequestData(), accessToken)) { return; } const TCHAR* Office365User = _T("user@mydomain.onmicrosoft.com"); IMailClientPtr oClient; oClient.CreateInstance(__uuidof(EAGetMailObjLib::MailClient)); IMailServerPtr oServer; oServer.CreateInstance(__uuidof(EAGetMailObjLib::MailServer)); oClient->LicenseCode = _T("TryIt"); oServer->Server = _T("outlook.office365.com"); oServer->User = Office365User; oServer->Password = accessToken; oServer->AuthType = MailServerAuthXOAUTH2; oServer->Protocol = MailServerEWS; oServer->SSLConnection = VARIANT_TRUE; oClient->Connect(oServer); IMailInfoCollectionPtr infos = oClient->GetMailInfoList(); for(long i = 0; i < infos->Count; i++) { IMailInfoPtr pInfo = infos->GetItem(i); _tprintf(_T("UIDL: %s\r\n"), (TCHAR*)pInfo->UIDL); _tprintf(_T("Index: %d\r\n"), pInfo->Index); _tprintf(_T("Size: %d\r\n"), pInfo->Size); _tprintf(_T("Read: %s\r\n"), (pInfo->Read == VARIANT_TRUE)?_T("TRUE"):_T("FALSE")); _tprintf(_T("Deleted: %s\r\n"), (pInfo->Deleted == VARIANT_TRUE)?_T("TRUE"):_T("FALSE")); IMailPtr oMail = oClient->GetMail(pInfo); TCHAR szFile[MAX_PATH+1]; memset(szFile, 0, sizeof(szFile)); ::wsprintf(szFile, _T("d:\\tempfolder\\%d.eml"), i); //save to local disk oMail->SaveAs(szFile, VARIANT_TRUE); oMail.Release(); // delete email from server oClient->Delete(pInfo); } oClient->Quit(); } catch(_com_error &ep) { _tprintf(_T("ERROR: %s\r\n"), (TCHAR*)ep.Description()); } }
[Delphi - Use EWS OAUTH 2.0 to retrieve email by impersonating user in Offic365] const MailServerPop3 = 0; MailServerImap4 = 1; MailServerEWS = 2; MailServerDAV = 3; // Auth type MailServerAuthLogin = 0; MailServerAuthCRAM5 = 1; MailServerAuthNTLM = 2; MailServerAuthXOAUTH2 = 3; CRYPT_MACHINE_KEYSET = 32; CRYPT_USER_KEYSET = 4096; function TForm1.RequestAccessToken(requestData: WideString): WideString; var httpRequest: TServerXMLHTTP; oauthParser: TOAuthResponseParser; fullRequest: OleVariant; status: integer; responseText: WideString; accessToken: WideString; tokenUri, tenant_id: WideString; begin result := ''; httpRequest := TServerXMLHTTP.Create(Application); fullRequest := requestData; // 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. tenant_id := '79a42c6f-5a9a-439b-a2ca-7aa1b0ed9776'; tokenUri := 'https://login.microsoftonline.com/' + tenant_id + '/oauth2/v2.0/token'; httpRequest.setOption(2, 13056); httpRequest.open('POST', tokenUri, true); httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); httpRequest.send(fullRequest); while( httpRequest.readyState <> 4 ) do begin try httpRequest.waitForResponse(1); Application.ProcessMessages(); except ShowMessage('Server response timeout (access token).'); exit; end; end; status := httpRequest.status; responseText := httpRequest.responseText; if (status < 200) or (status >= 300) then begin ShowMessage('Failed to get access token from server.' + responseText); exit; end; oauthParser := TOAuthResponseParser.Create(Application); oauthParser.Load(responseText); accessToken := oauthParser.AccessToken; if accessToken = '' then begin ShowMessage('Failed to parse access token from server response.'); exit; end; result := accessToken; end; function TForm1.GenerateRequestData(): WideString; const client_id: WideString = '8f54719b-4070-41ae-91ad-f48e3c793c5f'; client_secret: WideString = 'cbmYyGQjz[d29wL2ArcgoO7HLwJXL/-.'; scope: WideString = 'https://outlook.office365.com/.default'; begin result := 'client_id=' + client_id + '&client_secret=' + client_secret + '&scope=' + scope + '&grant_type=client_credentials'; end; procedure TForm1.ReceiveMail(); var Office365User, accessToken: WideString; oServer: TMailServer; oClient: TMailClient; oTools: TTools; oMail: IMail; infos: IMailInfoCollection; oInfo: IMailInfo; localInbox, fileName: WideString; i: Integer; begin try accessToken := RequestAccessToken(GenerateRequestData()); if accessToken = '' then exit; Office365User := 'user@mydomain.onmicrosoft.com'; // set current thread code page to system default code page. SetThreadLocale(GetSystemDefaultLCID()); oTools := TTools.Create(Application); // Create a folder named "inbox" under // current directory to store the email files localInbox := GetCurrentDir() + '\inbox'; oTools.CreateFolder(localInbox); oServer := TMailServer.Create(Application); oServer.Server := 'outlook.office365.com'; oServer.User := Office365User; oServer.Password := accessToken; oServer.AuthType := MailServerAuthXOAUTH2; oServer.Protocol := MailServerEWS; // Enable SSL Connection oServer.SSLConnection := true; oClient := TMailClient.Create(Application); oClient.LicenseCode := 'TryIt'; oClient.Connect1(oServer.DefaultInterface); ShowMessage('Connected!'); infos := oClient.GetMailInfoList(); ShowMessage(Format('Total %d email(s)', [infos.Count])); for i := 0 to infos.Count - 1 do begin oInfo := infos.Item[i]; ShowMessage(Format('Index: %d; Size: %d; UIDL: ' + oInfo.UIDL, [oInfo.Index, oInfo.Size])); // Generate a random file name by current local datetime, // You can use your method to generate the filename if you do not like it fileName := localInbox + '\' + oTools.GenFileName(i) + '.eml'; // Receive email from EWS server oMail := oClient.GetMail(oInfo); ShowMessage('From: ' + oMail.From.Address + #13#10 + 'Subject: ' + oMail.Subject); // Save email to local disk oMail.SaveAs(fileName, true); // Mark email as deleted from EWS server oClient.Delete(oInfo); end; // Quit and expunge emails marked as deleted from EWS server oClient.Quit; except on ep:Exception do ShowMessage('Error: ' + ep.Message); end; end; end.

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

Using EAGetMail POP3 & IMAP4 ActiveX Object
Registration-free COM with Manifest File
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 ActiveX Object References
EAGetMail POP3 & IMAP4 Component Samples

Online Tutorials

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

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

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