Delphi - Retrieve email using Microsoft OAuth 2.0 + EWS/Graph API/IMAP4/POP3 protocol from Office 365 in background service

You can retrieve email using traditional user/password authentication from Office 365 account by EWS/IMAP4/POP3 Protocol.

However Microsoft has disabled traditional user authentication in many tenants, switching to Microsoft OAuth (Modern Authentication) is strongly recommended now.

In this topic, I will introduce how to retrieve email using Delphi and Microsoft OAuth (Modern Authentication) in background service.

Installation

Before you can use the following sample codes, you should download the EAGetMail Installer and install it on your machine at first. Full sample projects are included in this installer.

Add reference

To better demonstrate how to retrieve email and parse email, let’s create a Delphi Standard EXE project at first, then add a TButton on the Form, double-click this button. It is like this:

Delphi console project

To use EAGetMail ActiveX Object in your Delphi project, the first step is “Add Unit file of EAGetMail to your project”. Please go to C:\Program Files\EAGetMail\Include\delphi or C:\Program Files (x86)\EAGetMail\Include\delphi folder, find EAGetMailObjLib_TLB.pas, and then copy this file to your project folder.

// include EAGetMailObjLib_TLB unit to your Delphi Project
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, EAGetMailObjLib_TLB, StdCtrls;

Then you can start to use it in your Delphi Project.

You can also create EAGetMailObjLib_TLB.pas manually by Delphi like this:

  • Delphi 7 or eariler version

    First of all, create a standard delphi project: select menu Project -> Import Type Library, checked EAGetMail ActiveX Object and click Create Unit. Then include EAGetMailObjLib_TLB in your project.

    add reference in Delphi
  • Delphi XE or later version

    First of all, create a standard delphi project: select menu Component -> Import component... -> Import a type library -> checked EAGetMail ActiveX Object, have Generate Component Wrapper checked and click “Create Unit”. Then include EAGetMailObjLib_TLB in your project.

Office 365 OAuth 2.0 client credentials grant

Normal OAuth requires user to input user and password in browser for authentication. Obviously, it is not suitable for background service.

The solution is granting admin consent to the azure application, then the application can use the client secret value to request the access token directly. This way doesn’t require user attending, it is suitable for background service.

This tutorial introduces how to register application for background service in Azure Portal, then assign the Graph API/EWS/SMTP/POP/IMAP API permission to the application and add the access right to the mailbox of specific user.

Register the application in Azure Portal

Sign in to the Azure Portal using the Microsoft account of the Office 365 administrator. If your account gives you access to more than one tenant, select your account in the top right corner, and set your portal session to the Azure AD tenant that you want.

Search Microsoft Entra ID (old name “Azure Active Directory”) and go to this service:

go to azure active directory

Register application

In the left-hand navigation pane, select the Microsoft Entra ID service, and then select App registrations -> New registration.

register app in azure

Input a name to to register the application:

register app in azure

Find the application id (client id) and tenant id

After the application is registered, you can click Overview to find the client id and tenant id. These are required parameters for requesting access token.

client int of azure app

Assign API permission

Now you need to assign API permission to the application by clicking API Permission -> Add a permission.

add api permission to app in azure

You don’t have to assign all the API permissions below to the application, just assign the API permission(s) you need.

Protocol Permission Scope
Graph API Mail.Send, Mail.ReadWrite https://graph.microsoft.com/.default
EWS full_access_as_app https://outlook.office365.com/.default
SMTP SMTP.AccessAsApp https://outlook.office365.com/.default
POP POP.AccessAsApp https://outlook.office365.com/.default
IMAP IMAP.AccessAsApp https://outlook.office365.com/.default

Graph API permission

Go to Microsoft APIs -> Microsoft Graph -> Application Permission ->

add graph api permission to app in azure

Add Mail.Send and Mail.ReadWrite permission

add Graph Mail.Send Mail.ReadWrite permission to app in azure

EWS and SMTP/POP/IMAP permission

Go to APIs in my organization uses -> Office 365 Exchange Online -> Application Permission ->

add exchange online permission to app in azure

Add full_access_app permission

add exchange online EWS permission to app in azure

Add POP.AccessAsApp permission

add exchange online POP permission to app in azure

Add IMAP.AccessAsApp permission

add exchange online IMAP permission to app in azure

Add SMTP.AccessAsApp permission

add exchange online SMTP permission to app in azure

Complete permissions list

api permission overview in azure

Create client secret

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

add client secret in azure add client secret in azure

Store client secret value

After client secret is created, store the client secret value to somewhere. It is another required parameter for requesting access token.

copy client secret value

Important

Please store client secret value by yourself, because it is hidden when you view it at next time.

Now you can use the client id, tenant id and client secret value to request access token. But to use SMTP/POP/IMAP protocol, you need to Register SMTP/POP/IMAP service principals in Exchange as well.

Important

You should create your client id and client secret, do not use the client id from example codes in production environment, it is used for test purpose. If you got "This app isn't verified" information, please click "Advanced" -> Go to ... for test.

Now you can use the following example codes to retrieve email with Graph API or EWS protocol:

Delphi - Retrieve email using Graph API + Microsoft OAuth 2.0 in background service - example

program Project1;
{$APPTYPE CONSOLE}

uses
    Windows, Messages, SysUtils, Variants, Classes, Graphics, ActiveX, MSXML2_TLB, EAGetMailObjLib_TLB;

const
    MailServerPop3 = 0;
    MailServerImap4 = 1;
    MailServerEWS = 2;
    MailServerDAV = 3;
    MailServerMsGraph = 4;

    // Auth type
    MailServerAuthLogin = 0;
    MailServerAuthCRAM5 = 1;
    MailServerAuthNTLM = 2;
    MailServerAuthXOAUTH2 = 3;

    CRYPT_MACHINE_KEYSET = 32;
    CRYPT_USER_KEYSET = 4096;
    CERT_SYSTEM_STORE_CURRENT_USER = 65536;
    CERT_SYSTEM_STORE_LOCAL_MACHINE = 131072;

    // GetMailInfosParam Flags
    GetMailInfos_All = 1;
    GetMailInfos_NewOnly = 2;
    GetMailInfos_ReadOnly = 4;
    GetMailInfos_SeqRange = 8;
    GetMailInfos_UIDRange = 16;
    GetMailInfos_PR_ENTRYID = 32;
    GetMailInfos_DateRange = 64;
    GetMailInfos_OrderByDateTime = 128;

function 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(nil);

    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 := '2ea4955d-830e-4aa7-8ab5-661a6b9aa84d';
    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);
        except
            writeln('Server response timeout (access token).');
            exit;
        end;
    end;

    status := httpRequest.status;
    responseText := httpRequest.responseText;

    if (status < 200) or (status >= 300) then
    begin
        writeln('Failed to get access token from server.' + responseText);
        exit;
    end;

    oauthParser := TOAuthResponseParser.Create(nil);
    oauthParser.Load(responseText);

    accessToken := oauthParser.AccessToken;

    if accessToken = '' then
    begin
        writeln('Failed to parse access token from server response.');
        exit;
    end;

    result := accessToken;
end;

function GenerateRequestData(): WideString;
const
    client_id: WideString = 'b22194da-44d6-4320-a067-e86a275d6fa4';
    client_secret: WideString = 'VTO8Q~eo0JCXc291jcM4wnhZ_GXyKMu.';
    scope: WideString = 'https://graph.microsoft.com/.default';
begin
    result := 'client_id=' + client_id
            + '&client_secret=' + client_secret
            + '&scope=' + scope
            + '&grant_type=client_credentials';
end;

procedure RetrieveEmail();
var
    accessToken: WideString;
    Office365User: WideString;
    oServer: TMailServer;
    oClient: TMailClient;
    oTools: TTools;
    oMail: IMail;
    infos: IMailInfoCollection;
    oInfo: IMailInfo;
    localInbox, fileName: WideString;
    i: Integer;
begin

    try
        Office365User := 'user@mydomain.onmicrosoft.com';

        accessToken := RequestAccessToken(GenerateRequestData());
        if accessToken = '' then
        exit;

        // set current thread code page to system default code page.
        SetThreadLocale(GetSystemDefaultLCID());
        oTools := TTools.Create(nil);

        // Create a folder named "inbox" under
        // current directory to store the email files
        localInbox := GetCurrentDir() + '\inbox';
        oTools.CreateFolder(localInbox);

        oServer := TMailServer.Create(nil);
        // Office 365 Graph API Server
        oServer.Server := 'graph.microsoft.com';
        // Use OAUTH 2.0
        oServer.AuthType := MailServerAuthXOAUTH2;

        oServer.User := Office365User;
        // Use access token as password
        oServer.Password := accessToken;
        // Use Graph API Protocol
        oServer.Protocol := MailServerMsGraph;

        // Enable SSL Connection
        oServer.SSLConnection := true;


        oClient := TMailClient.Create(nil);
        oClient.LicenseCode := 'TryIt';

        writeln('Connecting ' + oServer.Server + ' ...');
        oClient.Connect1(oServer.DefaultInterface);
        writeln('Connected!');

        // Get new email only, if you want to get all emails, please remove this line
        oClient.GetMailInfosParam.GetMailInfosOptions := GetMailInfos_NewOnly;

        infos := oClient.GetMailInfoList();
        writeln(Format('Total %d email(s)', [infos.Count]));

        for i := 0 to infos.Count - 1 do
        begin
            oInfo := infos.Item[i];

            writeln(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);

            writeln('From: ' + oMail.From.Address + #13#10 +
                'Subject: ' + oMail.Subject);

            // Save email to local disk
            oMail.SaveAs(fileName, true);

            // Mark email as read to prevent retrieving this email again.
            oClient.MarkAsRead(oInfo, true);

            // If you want to delete current email, please use Delete method instead of MarkAsRead
            // oClient.Delete(oInfo);
        end;

        // Quit and expunge emails marked as deleted from IMAP server
        oClient.Quit;
    except
        on ep:Exception do
        writeln('Error: ' + ep.Message);
    end;

end;

begin

    CoInitialize(nil);

    writeln('+------------------------------------------------------------------+');
    writeln('  Sign in with MS OAuth');
    writeln('   If you got "This app is not verified" information in Web Browser, ');
    writeln('      click "Advanced" -> Go to ... to continue test.');
    writeln('+------------------------------------------------------------------+');
    writeln('');

    writeln('Press ENTER key to sign in...');
    readln;

    RetrieveEmail();

    writeln('Press ENTER key to quit...');
    readln;

end.

Delphi - Retrieve email using EWS + Microsoft OAuth 2.0 in background service - example

program Project1;
{$APPTYPE CONSOLE}

uses
    Windows, Messages, SysUtils, Variants, Classes, Graphics, ActiveX, MSXML2_TLB, EAGetMailObjLib_TLB;

const
    MailServerPop3 = 0;
    MailServerImap4 = 1;
    MailServerEWS = 2;
    MailServerDAV = 3;
    MailServerMsGraph = 4;

    // Auth type
    MailServerAuthLogin = 0;
    MailServerAuthCRAM5 = 1;
    MailServerAuthNTLM = 2;
    MailServerAuthXOAUTH2 = 3;

    CRYPT_MACHINE_KEYSET = 32;
    CRYPT_USER_KEYSET = 4096;
    CERT_SYSTEM_STORE_CURRENT_USER = 65536;
    CERT_SYSTEM_STORE_LOCAL_MACHINE = 131072;

    // GetMailInfosParam Flags
    GetMailInfos_All = 1;
    GetMailInfos_NewOnly = 2;
    GetMailInfos_ReadOnly = 4;
    GetMailInfos_SeqRange = 8;
    GetMailInfos_UIDRange = 16;
    GetMailInfos_PR_ENTRYID = 32;
    GetMailInfos_DateRange = 64;
    GetMailInfos_OrderByDateTime = 128;

function 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(nil);

    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 := '2ea4955d-830e-4aa7-8ab5-661a6b9aa84d';
    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);
        except
            writeln('Server response timeout (access token).');
            exit;
        end;
    end;

    status := httpRequest.status;
    responseText := httpRequest.responseText;

    if (status < 200) or (status >= 300) then
    begin
        writeln('Failed to get access token from server.' + responseText);
        exit;
    end;

    oauthParser := TOAuthResponseParser.Create(nil);
    oauthParser.Load(responseText);

    accessToken := oauthParser.AccessToken;

    if accessToken = '' then
    begin
        writeln('Failed to parse access token from server response.');
        exit;
    end;

    result := accessToken;
end;

function GenerateRequestData(): WideString;
const
    client_id: WideString = 'b22194da-44d6-4320-a067-e86a275d6fa4';
    client_secret: WideString = 'VTO8Q~eo0JCXc291jcM4wnhZ_GXyKMu.';
    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 RetrieveEmail();
var
    accessToken: WideString;
    Office365User: WideString;
    oServer: TMailServer;
    oClient: TMailClient;
    oTools: TTools;
    oMail: IMail;
    infos: IMailInfoCollection;
    oInfo: IMailInfo;
    localInbox, fileName: WideString;
    i: Integer;
begin

    try
        Office365User := 'user@mydomain.onmicrosoft.com';

        accessToken := RequestAccessToken(GenerateRequestData());
        if accessToken = '' then
        exit;

        // set current thread code page to system default code page.
        SetThreadLocale(GetSystemDefaultLCID());
        oTools := TTools.Create(nil);

        // Create a folder named "inbox" under
        // current directory to store the email files
        localInbox := GetCurrentDir() + '\inbox';
        oTools.CreateFolder(localInbox);

        oServer := TMailServer.Create(nil);
        // Office 365 Server
        oServer.Server := 'outlook.office365.com';
        // Use OAUTH 2.0
        oServer.AuthType := MailServerAuthXOAUTH2;

        oServer.User := Office365User;
        // Use access token as password
        oServer.Password := accessToken;
        // Use EWS Protocol
        oServer.Protocol := MailServerEWS;

        // Enable SSL Connection
        oServer.SSLConnection := true;


        oClient := TMailClient.Create(nil);
        oClient.LicenseCode := 'TryIt';

        writeln('Connecting ' + oServer.Server + ' ...');
        oClient.Connect1(oServer.DefaultInterface);
        writeln('Connected!');

        // Get new email only, if you want to get all emails, please remove this line
        oClient.GetMailInfosParam.GetMailInfosOptions := GetMailInfos_NewOnly;

        infos := oClient.GetMailInfoList();
        writeln(Format('Total %d email(s)', [infos.Count]));

        for i := 0 to infos.Count - 1 do
        begin
            oInfo := infos.Item[i];

            writeln(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);

            writeln('From: ' + oMail.From.Address + #13#10 +
                'Subject: ' + oMail.Subject);

            // Save email to local disk
            oMail.SaveAs(fileName, true);

            // Mark email as read to prevent retrieving this email again.
            oClient.MarkAsRead(oInfo, true);

            // If you want to delete current email, please use Delete method instead of MarkAsRead
            // oClient.Delete(oInfo);
        end;

        // Quit and expunge emails marked as deleted from IMAP server
        oClient.Quit;
    except
        on ep:Exception do
        writeln('Error: ' + ep.Message);
    end;

end;

begin

    CoInitialize(nil);

    writeln('+------------------------------------------------------------------+');
    writeln('  Sign in with MS OAuth');
    writeln('   If you got "This app is not verified" information in Web Browser, ');
    writeln('      click "Advanced" -> Go to ... to continue test.');
    writeln('+------------------------------------------------------------------+');
    writeln('');

    writeln('Press ENTER key to sign in...');
    readln;

    RetrieveEmail();

    writeln('Press ENTER key to quit...');
    readln;

end.

Register SMTP/POP/IMAP service principals in Exchange

Although the application is consented by the tenant admin, but to access SMTP/POP/IMAP service, the tenant administrator still need to register your application as service principal in Exchange via Exchange Online PowerShell. This is enabled by the New-ServicePrincipal cmdlet.

New-ServicePrincipal -AppId <APPLICATION_ID> -ServiceId <OBJECT_ID>

Find APPLICATION_ID and OBJECT_ID

You should find your APPLICATION_ID and OBJECT_ID before running above cmdlet. Go to Overview -> Managed application in local directory:

Managed application in local directory

After you click your application name in Managed application in l..., you can see Application ID and Object ID for New-ServicePrincipal cmdlet.

find object id in Managed application in local directory

Open Exchange Online PowerShell

Now you need to open Exchange Online PowerShell to run the cmdlet. If you have not installed the module, you can use the Install-Module cmdlet to install the module from the PowerShell Gallery.

Install-Module -Name ExchangeOnlineManagement

After you’ve installed the module, open a PowerShell window and load the module by running the following command:

Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -UserPrincipalName "admin@yourdomain.onmicrosoft.com"

Create service principal

After Exchange Online PowerShell is connected successfully, run the following cmdlet to create a new service principal: The ServiceId is the OBJECT_ID and the AppId is APPLICATION_ID found in Find APPLICATION_ID and OBJECT_ID

New-ServicePrincipal -AppId "b22194da-44d6-4320-a067-e86a275d6fa4" -ServiceId "71941e67-ef24-45e8-bd22-dfd53790bb77"

Query service principal

After you create the service principal, you can query it by:

Get-ServicePrincipal

Add permission to specific user

You can now add the specific mailboxes in the tenant that will be allowed to be access by your application. This is done with the Add-MailboxPermission cmdlet.

Add-MailboxPermission -Identity <mailboxIdParameter> -User <SecurityPrincipalIdParameter|OBJECT_ID>  -AccessRights <MailboxRights[]>

For example:

Add-MailboxPermission -Identity "grant-test@emailarchitect.net" -User "71941e67-ef24-45e8-bd22-dfd53790bb77" -AccessRights FullAccess

Query permission

You can also query the permission by:

Get-MailboxPermission -Identity "grant-test@emailarchitect.net"

Now you can use IMAP or POP3 protocol to retrieve email by the following codes:

Delphi - Retrieve email using IMAP4 + Microsoft OAuth 2.0 in background service - example

program Project1;
{$APPTYPE CONSOLE}

uses
    Windows, Messages, SysUtils, Variants, Classes, Graphics, ActiveX, MSXML2_TLB, EAGetMailObjLib_TLB;

const
    MailServerPop3 = 0;
    MailServerImap4 = 1;
    MailServerEWS = 2;
    MailServerDAV = 3;
    MailServerMsGraph = 4;

    // Auth type
    MailServerAuthLogin = 0;
    MailServerAuthCRAM5 = 1;
    MailServerAuthNTLM = 2;
    MailServerAuthXOAUTH2 = 3;

    CRYPT_MACHINE_KEYSET = 32;
    CRYPT_USER_KEYSET = 4096;
    CERT_SYSTEM_STORE_CURRENT_USER = 65536;
    CERT_SYSTEM_STORE_LOCAL_MACHINE = 131072;

    // GetMailInfosParam Flags
    GetMailInfos_All = 1;
    GetMailInfos_NewOnly = 2;
    GetMailInfos_ReadOnly = 4;
    GetMailInfos_SeqRange = 8;
    GetMailInfos_UIDRange = 16;
    GetMailInfos_PR_ENTRYID = 32;
    GetMailInfos_DateRange = 64;
    GetMailInfos_OrderByDateTime = 128;

function 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(nil);

    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 := '2ea4955d-830e-4aa7-8ab5-661a6b9aa84d';
    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);
        except
            writeln('Server response timeout (access token).');
            exit;
        end;
    end;

    status := httpRequest.status;
    responseText := httpRequest.responseText;

    if (status < 200) or (status >= 300) then
    begin
        writeln('Failed to get access token from server.' + responseText);
        exit;
    end;

    oauthParser := TOAuthResponseParser.Create(nil);
    oauthParser.Load(responseText);

    accessToken := oauthParser.AccessToken;

    if accessToken = '' then
    begin
        writeln('Failed to parse access token from server response.');
        exit;
    end;

    result := accessToken;
end;

function GenerateRequestData(): WideString;
const
    client_id: WideString = 'b22194da-44d6-4320-a067-e86a275d6fa4';
    client_secret: WideString = 'VTO8Q~eo0JCXc291jcM4wnhZ_GXyKMu.';
    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 RetrieveEmail();
var
    accessToken: WideString;
    Office365User: WideString;
    oServer: TMailServer;
    oClient: TMailClient;
    oTools: TTools;
    oMail: IMail;
    infos: IMailInfoCollection;
    oInfo: IMailInfo;
    localInbox, fileName: WideString;
    i: Integer;
begin

    try
        Office365User := 'grant-test@emailarchitect.net';

        accessToken := RequestAccessToken(GenerateRequestData());
        if accessToken = '' then
        exit;

        // set current thread code page to system default code page.
        SetThreadLocale(GetSystemDefaultLCID());
        oTools := TTools.Create(nil);

        // Create a folder named "inbox" under
        // current directory to store the email files
        localInbox := GetCurrentDir() + '\inbox';
        oTools.CreateFolder(localInbox);

        oServer := TMailServer.Create(nil);
        // Office 365 Server
        oServer.Server := 'outlook.office365.com';
        // Use OAUTH 2.0
        oServer.AuthType := MailServerAuthXOAUTH2;

        oServer.User := Office365User;
        // Use access token as password
        oServer.Password := accessToken;
        // Use IMAP4 Protocol
        oServer.Protocol := MailServerImap4;

        // Enable SSL Connection
        oServer.SSLConnection := true;
        // Set IMAP SSL Port
        oServer.Port := 993;

        oClient := TMailClient.Create(nil);
        oClient.LicenseCode := 'TryIt';

        writeln('Connecting ' + oServer.Server + ' ...');
        oClient.Connect1(oServer.DefaultInterface);
        writeln('Connected!');

        // Get new email only, if you want to get all emails, please remove this line
        oClient.GetMailInfosParam.GetMailInfosOptions := GetMailInfos_NewOnly;

        infos := oClient.GetMailInfoList();
        writeln(Format('Total %d email(s)', [infos.Count]));

        for i := 0 to infos.Count - 1 do
        begin
            oInfo := infos.Item[i];

            writeln(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);

            writeln('From: ' + oMail.From.Address + #13#10 +
                'Subject: ' + oMail.Subject);

            // Save email to local disk
            oMail.SaveAs(fileName, true);

            // Mark email as read to prevent retrieving this email again.
            oClient.MarkAsRead(oInfo, true);

            // If you want to delete current email, please use Delete method instead of MarkAsRead
            // oClient.Delete(oInfo);
        end;

        // Quit and expunge emails marked as deleted from IMAP server
        oClient.Quit;
    except
        on ep:Exception do
        writeln('Error: ' + ep.Message);
    end;

end;

begin

    CoInitialize(nil);

    writeln('+------------------------------------------------------------------+');
    writeln('  Sign in with MS OAuth');
    writeln('   If you got "This app is not verified" information in Web Browser, ');
    writeln('      click "Advanced" -> Go to ... to continue test.');
    writeln('+------------------------------------------------------------------+');
    writeln('');

    writeln('Press ENTER key to sign in...');
    readln;

    RetrieveEmail();

    writeln('Press ENTER key to quit...');
    readln;

end.

Access token lifetime

You don’t have to request access token every time. By default, access token expiration time is 3600 seconds, you can reuse the access token repeatedly before it is expired.

TLS 1.2 protocol

TLS is the successor of SSL, more and more SMTP servers require TLS 1.2 encryption now.

If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2, you need to enable TLS 1.2 protocol in your operating system like this:

Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012

EA Oauth Service for Office 365

If you are not the tenant administrator and you don’t have the permission to create or grant the application in Azure, or if your code is too complex or out of maintenance, and you don’t want to change anything in your source codes, then you can have a try with EA Oauth Service for Offic365. It provides an easy way for the legacy email application that doesn’t support OAUTH 2.0 to send and retrieve email from Office 365 without changing any codes. SMTP, POP, IMAP and SSL/TLS protocols are supported.

Appendix

Comments

If you have any comments or questions about above example codes, please click here to add your comments.