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/2010 or later version).

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; // Add EAGetMail unit

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;

var
    Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
    oMail: IMail;
    oClient: TMailClient;
    oServer: TMailServer;
    oTools: TTools;
    infos: OleVariant;
    i, UBound, Count: integer;
    oInfo: IMailInfo;
    mailFolder: WideString;
    fileName: WideString;
begin
    try
        oTools := TTools.Create(Application);

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

        oServer := TMailServer.Create(Application);
        oServer.Server := 'exch.emailarchitect.net';

        // Please use domain\user as the user name
        oServer.User := 'emailarchitect.net\tester';
        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.GetMailInfos();
        UBound := VarArrayHighBound( infos, 1 );
        Count := UBound+1;
        ShowMessage(Format('Total %d email(s)', [Count]));

        for i := 0 to UBound do
        begin
            oInfo := IDispatch(VarArrayGet(infos, i)) as IMailInfo ;
            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 := mailFolder + '\' + 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 );

            // Delete email from Exchange server
            oClient.Delete(oInfo);
        end;

        // Quit 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 SearchFolder(folders: OleVariant; name: WideString):IImap4Folder;
    private
        { Private declarations }
    public
        { Public declarations }
    end;

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

var
    Form1: TForm1;

implementation

{$R *.dfm}

function TForm1.SearchFolder(folders: OleVariant; name: WideString)
:IImap4Folder;
var
    i, UBound: integer;
    folder: IImap4Folder;
begin
    UBound := VarArrayHighBound(folders, 1 );
    for i:= 0 to UBound do
    begin
        folder := IDispatch(VarArrayGet(folders,i)) as IImap4Folder;
        if CompareText( folder.Name, name ) = 0 then
        begin
        Result := folder;
        exit;
        end;

        // Search folder in sub-folders
        folder := SearchFolder( folder.SubFolders, name );
        if not (folder = nil ) then
        begin
            Result := folder;
            exit;
        end;
    end;
    // No folder found
    Result := nil;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
    oMail: IMail;
    oClient: TMailClient;
    oServer: TMailServer;
    oTools: TTools;
    infos: OleVariant;
    i, UBound, Count: integer;
    oInfo: IMailInfo;
    mailFolder: WideString;
    fileName: WideString;
    oFolder: IImap4Folder;
begin
    try
        oTools := TTools.Create(Application);

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

        oServer := TMailServer.Create(Application);
        oServer.Server := 'exch.emailarchitect.net';

        // Please use domain\user as the user name
        oServer.User := 'emailarchitect.net\tester';
        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!' );

        // Search folder based on folder name
        oFolder := SearchFolder( oClient.Imap4Folders, 'Deletexd Items' );
        if oFolder = nil then
        begin
            raise Exception.Create('No folder found');
        end;

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

        infos := oClient.GetMailInfos();
        UBound := VarArrayHighBound( infos, 1 );
        Count := UBound+1;
        ShowMessage(Format('Total %d email(s)', [Count]));

        for i := 0 to UBound do
        begin
            oInfo := IDispatch(VarArrayGet(infos, i)) as IMailInfo ;
            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 := mailFolder + '\' + oTools.GenFileName(i) + '.eml';

            // Receive email from IMAP4 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 IMAP4 server
            oClient.Delete(oInfo);
        end;

        // Quit and purge emails marked as deleted from IMAP4 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.