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.


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 6.0, VBScript, Visual C++, Delphi] The following example demonstrates how to receive email using Gmail IMAP OAUTH, but it doesn't demonstrates the events and mail parsing usage. To get the full samples of EAGetMail, please refer to Samples section.

[Visual Basic 6.0]
Public Sub ReceiveMail( _
ByVal userEmail As String, _
ByVal accessToken As String)
    
    Const MailServerPop3 = 0
    Const MailServerImap4 = 1
    Const MailServerEWS = 2
    Const MailServerDAV = 3

    Const MailServerAuthLogin = 0
    Const MailServerAuthCRAM5 = 1
    Const MailServerAuthNTLM = 2
    Const MailServerAuthXOAUTH2 = 3
    
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"
    
    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "outlook.office365.com"
    oServer.User = userEmail
    oServer.Password = accessToken
    oServer.Protocol = MailServerEWS
    oServer.AuthType = MailServerAuthXOAUTH2
    
    oServer.SSLConnection = True
    
    On Error GoTo ErrorHandle
        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


[VBScript] Sub ReceiveMail( _ ByVal userEmail, _ ByVal accessToken) Const MailServerPop3 = 0 Const MailServerImap4 = 1 Const MailServerEWS = 2 Const MailServerDAV = 3 Const MailServerAuthLogin = 0 Const MailServerAuthCRAM5 = 1 Const MailServerAuthNTLM = 2 Const MailServerAuthXOAUTH2 = 3 Dim oClient Set oClient = CreateObject("EAGetMailObj.MailClient") oClient.LicenseCode = "TryIt" Dim oServer Set oServer = CreateObject("EAGetMailObj.MailServer") oServer.Server = "outlook.office365.com" oServer.User = userEmail oServer.Password = accessToken oServer.Protocol = MailServerEWS oServer.AuthType = MailServerAuthXOAUTH2 oServer.SSLConnection = True oServer.Port = 993 'SSL IMAP4 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 End Sub
[Visual C++] #include "stdafx.h" #include <windows.h> #include "eagetmailobj.tlh" using namespace EAGetMailObjLib; void ReceiveMail( LPCTSTR userEmail, LPCTSTR accessToken) { ::CoInitialize(NULL); const int MailServerPop3 = 0; const int MailServerImap4 = 1; const int MailServerEWS = 2; const int MailServerDAV = 3; const int MailServerAuthLogin = 0; const int MailServerAuthCRAM5 = 1; const int MailServerAuthNTLM = 2; const int MailServerAuthXOAUTH2 = 3; try { 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 = userEmail; oServer->Password = accessToken; oServer->Protocol = MailServerEWS; oServer->AuthType = MailServerAuthXOAUTH2; 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()); } ::CoUninitialize(); }
[Delphi] const MailServerPop3 = 0; MailServerImap4 = 1; MailServerEWS = 2; MailServerDAV = 3; // Auth type MailServerAuthLogin = 0; MailServerAuthCRAM5 = 1; MailServerAuthNTLM = 2; MailServerAuthXOAUTH2 = 3; var Form1: TForm1; implementation {$R *.dfm} procedure ReceiveMail(userEmail: WideString; accessToken: WideString); var oServer: TMailServer; oClient: TMailClient; oTools: TTools; oMail: IMail; infos: IMailInfoCollection; oInfo: IMailInfo; localInbox, fileName: WideString; i: Integer; begin try // 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 := userEmail; oServer.Password := accessToken; oServer.Protocol := MailServerEWS; oServer.AuthType := MailServerAuthXOAUTH2; // 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 IMAP 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 IMAP server oClient.Delete(oInfo); end; // Quit and expunge emails marked as deleted from IMAP server oClient.Quit; except on ep:Exception do ShowMessage('Error: ' + ep.Message); end; end; end.

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

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