Retrieve Email from IMAP4 server in Delphi

In previous section, I introduced retrieving email from POP3 server in Delphi. In this section, I will introduce the IMAP4 server.

Introduction

IMAP4 protocol is different with POP3 protocol. First of all, IMAP4 supports retrieving email from different mail folder and folder management. Secondly, IMAP4 supports mail flags management. Therefore, we can do more things with IMAP4 server. To better understand the IMAP4 protocol, please see the following examples.

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 IMAP4 inbox]

The following example codes demonstrate how to download email from IMAP4 server default mailbox. 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 := 'imap4.emailarchitect.net';
        oServer.User := 'test@emailarchitect.net';
        oServer.Password := 'testpassword';
        oServer.Protocol := MailServerImap4;

        // Set IMAP4 port
        oServer.Port := 143;

        // If your server requires SSL connection
        // Please add the following codes
        // oServer.SSLConnection := true;
        // oServer.Port := 993;

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

Because IMAP4 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 IMAP4 account. 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);
        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 := 'imap4.emailarchitect.net';
        oServer.User := 'test@emailarchitect.net';
        oServer.Password := 'testpassword';
        oServer.Protocol := MailServerImap4;

        // Set IMAP4 port
        oServer.Port := 143;

        // If your server requires SSL connection
        // Please add the following codes
        // oServer.SSLConnection := true;
        // oServer.Port := 993;

        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 Web Service protocol.

Appendix

Comments

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