Retrieve Email from Exchange Server with Web Service (EWS) in Delphi

In previous section, I introduced how to retrieve email from IMAP4 server. In this section, I will introduce the Exchange Web Service (EWS) protocol (Exchange 2007-2019/Office 365).

Introduction

Exchange Web Service (EWS) protocol is similar with IMAP4 protocol. First of all, it supports retrieving email from different mail folder and folder management. Secondly, Exchange Web Service supports mail read flag management. Therefore, we can do more things with Exchange server. To better understand the Exchange Web Service protocol, please see the following examples.

Exchange Server supports POP3/IMAP4 protocol as well, but in Exchange 2007 or later version, POP3/IMAP4 service is disabled by default. If you don’t want to use POP3/IMAP4 to download email from Exchange Server, you can use Exchange Web Service (Exchange 2007/2010/2013/2016 or later version) or WebDAV (Exchange 2000/2003) protocol.

Office 365 also supports EWS protocol.

Note

Remarks: All of examples in this section are based on first section: A simple Delphi project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[Delphi Example - Retrieve email from Exchange INBOX]

The following example codes demonstrate how to download email from Exchange 2007/2010/2013/2016 server default mailbox using EWS protocol. In order to run it correctly, please change email server, user, password, folder, file name values.

Note

To get the full sample projects, please refer to Samples section.

unit Unit1;

interface

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

type
    TForm1 = class(TForm)
        Button1: TButton;
        procedure Button1Click(Sender: TObject);
    private
        { Private declarations }
    public
        { Public declarations }
    end;

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


var
    Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
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 := 'exch.emailarchitect.net';

        // Please use domain\user or full email address as the user name
        oServer.User := 'tester@emailarchitect.net';
        oServer.Password := 'testpassword';
        oServer.Protocol := MailServerEWS;

        // By default, Exchange Web Service (EWS) requires SSL connection
        // Please ignore Port property for EWS and WebDAV protocol
        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 Exchange 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 Exchange server
                oClient.Delete(oInfo);
            end;

        // Quit and expunge emails marked as deleted from Exchange server
        oClient.Quit;

    except
        on ep:Exception do
            ShowMessage('Error: ' + ep.Message);
    end;

end;

end.

Because Exchange Web Service protocol supports folder access, so we can retrieve email from other mailbox rather than default “INBOX”. POP3 protocol doesn’t support this feature.

[Delphi Example - Retrieve email from “Deleted Items”]

The following example codes demonstrate how to retrieve emails from “Deleted Items” in an Exchange account.

Note

To get the full sample projects, please refer to Samples section.

unit Unit1;

interface

uses
    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
    Dialogs, StdCtrls, EAGetMailObjLib_TLB; // Add EAGetMail unit

type
    TForm1 = class(TForm)
        Button1: TButton;
        procedure Button1Click(Sender: TObject);
        function FindFolder(folderPath: WideString; folders: IFolderCollection): IImap4Folder;
    private
        { Private declarations }
    public
        { Public declarations }
    end;

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


var
    Form1: TForm1;

implementation

{$R *.dfm}

function TForm1.FindFolder(folderPath: WideString; folders: IFolderCollection) :IImap4Folder;
var
    i: integer;
    folder: IImap4Folder;
begin

    for i:= 0 to folders.Count - 1 do
        begin
            folder := folders.Item[i];
            if CompareText(folder.LocalPath, folderPath) = 0 then
                begin
                    result := folder;
                    exit;
                end;

            // Search folder in sub-folders
            folder := FindFolder(folderPath, folder.SubFolderList);
            if not (folder = nil ) then
                begin
                    result := folder;
                    exit;
                end;
        end;

    // No folder found
    result := nil;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
    oServer: TMailServer;
    oClient: TMailClient;
    oTools: TTools;
    oMail: IMail;
    oFolder: IImap4Folder;
    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 := 'exch.emailarchitect.net';

        // Please use domain\user or full email address as the user name
        oServer.User := 'tester@emailarchitect.net';
        oServer.Password := 'testpassword';
        oServer.Protocol := MailServerEWS;

        // By default, Exchange Web Service (EWS) requires SSL connection
        // Please ignore Port property for EWS and WebDAV protocol
        oServer.SSLConnection := true;

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

        oClient.Connect1(oServer.DefaultInterface);
        ShowMessage('Connected!');

        oFolder := FindFolder('Deleted Items', oClient.GetFolderList());
        if oFolder = nil then
            raise Exception.Create('No folder found');

         // Select this folder
        oClient.SelectFolder(oFolder);

        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 Exchange 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 Exchange server
                oClient.Delete(oInfo);
            end;

        // Quit and expunge emails marked as deleted from Exchange server
        oClient.Quit;

    except
        on ep:Exception do
            ShowMessage('Error: ' + ep.Message);
    end;

end;

end.

Next Section

At next section I will introduce how to retrieve email from Exchange Server with WebDAV protocol.

Appendix

Comments

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