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;

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 := 'imap.emailarchitect.net';
        oServer.User := 'test@emailarchitect.net';
        oServer.Password := 'testpassword';
        oServer.Protocol := MailServerImap4;

        // Enable SSL Connection, most modern email servers require SSL/TLS by default
        oServer.SSLConnection := true;
        oServer.Port := 993;

        // If your IMAP doesn't deploy SSL connection
        // Please use
        // oServer.SSLConnection := false;
        // oServer.Port := 143;

        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.

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 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 := 'imap.emailarchitect.net';
        oServer.User := 'test@emailarchitect.net';
        oServer.Password := 'testpassword';
        oServer.Protocol := MailServerImap4;

        // Enable SSL Connection, most modern email servers require SSL/TLS by default
        oServer.SSLConnection := true;
        oServer.Port := 993;

        // If your IMAP doesn't deploy SSL connection
        // Please use
        // oServer.SSLConnection := false;
        // oServer.Port := 143;

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

TLS 1.2

TLS is the successor of SSL, more and more Email 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, and you got connection error with SSL/TLS connection, 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

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.