Retrieve Email over SSL connection in Delphi

In previous section, I introduced how to retrieve email from Exchange Server with WebDAV protocol. In this section, I will introduce how to retrieve email over SSL connection in Delphi.

Introduction

SSL and TLS

SSL connection encrypts data between the email component and POP3 server or IMAP4 server to protect user, password and email content in TCP/IP level. Now this technology is commonly used and many email servers are deployed with SSL such as Gmail, Yahoo and Hotmail.

There are two ways to deploy SSL on email server:

  • Implicit SSL

    Deploying SSL on another port (POP3: 995 port or IMAP4: 993 port) directly. This is most common way.

  • Explicit SSL (TLS)

    Using STARTTLS or STLS command to switch SSL channel on normal port (POP3: 110 port or IMAP4: 143 port);

EAGetMail POP3 component supports both ways. Please see the following example codes:

For Exchange Web Service/WebDAV protocol, the SSL is based on HTTPS connection, so you just need to set SSLConnection property and simply ignore Port property. Notice: Exchange Web Service requires SSL connection by default.

[Delphi Example - SSL/TLS]

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

    ConnectSSLAuto = 0;
    ConnectSSL = 1;
    ConnectTLS = 2;

// Retrieve email by normal TCP/IP without SSL connection
// POP3
oServer := TMailServer.Create(Application);
oServer.Server := 'pop3.emailarchitect.net';
oServer.User := 'test@emailarchitect.net';
oServer.Password := 'testpassword';
oServer.Protocol := MailServerPop3;
oServer.Port := 110;

// IMAP4
oServer := TMailServer.Create(Application);
oServer.Server := 'imap4.emailarchitect.net';
oServer.User := 'test@emailarchitect.net';
oServer.Password := 'testpassword';
oServer.Protocol := MailServerImap4;
oServer.Port := 143;

// Retrieve email over SSL connection with direct SSL.
// POP3 SSL
oServer := TMailServer.Create(Application);
oServer.Server := 'pop3.emailarchitect.net';
oServer.User := 'test@emailarchitect.net';
oServer.Password := 'testpassword';
oServer.Protocol := MailServerPop3;
oServer.SSLConnection := true;
oServer.Port := 995;

// IMAP4 SSL
oServer := TMailServer.Create(Application);
oServer.Server := 'imap4.emailarchitect.net';
oServer.User := 'test@emailarchitect.net';
oServer.Password := 'testpassword';
oServer.Protocol := MailServerImap4;
oServer.SSLConnection := true;
oServer.Port := 993;

// Retrieve email by SSL connection with STARTTLS or TLS command switching
// POP3 TLS
oServer := TMailServer.Create(Application);
oServer.Server := 'pop3.emailarchitect.net';
oServer.User := 'test@emailarchitect.net';
oServer.Password := 'testpassword';
oServer.Protocol := MailServerPop3;
oServer.SSLConnection := true;
oServer.Port := 110;
oServer.SSLType := ConnectTLS;

// IMAP4 STARTTLS
oServer := TMailServer.Create(Application);
oServer.Server := 'imap4.emailarchitect.net';
oServer.User := 'test@emailarchitect.net';
oServer.Password := 'testpassword';
oServer.Protocol := MailServerImap4;
oServer.SSLConnection := true;
oServer.Port := 143;
oServer.SSLType := ConnectTLS;

// WebDAV
oServer := TMailServer.Create(Application);
oServer.Server := 'exch.emailarchitect.net';
oServer.User := 'emailarchitect.net\tester';
oServer.Password := 'testpassword';
oServer.Protocol := MailServerDAV;

// WebDAV SSL
oServer := TMailServer.Create(Application);
oServer.Server := 'exch.emailarchitect.net';
oServer.User := 'emailarchitect.net\tester';
oServer.Password := 'testpassword';
oServer.Protocol := MailServerDAV;
oServer.SSLConnection := true;

// Exchange Web Service (EWS) SSL
oServer := TMailServer.Create(Application);
oServer.Server := 'exch.emailarchitect.net';
oServer.User := 'emailarchitect.net\tester';
oServer.Password := 'testpassword';
oServer.Protocol := MailServerEWS;
oServer.SSLConnection := true;

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 POP3 server over SSL on 995 port]

The following example codes demonstrate how to retrieve emails from POP3 server over SSL connection on 995 port. 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 := 'pop3.emailarchitect.net';
        oServer.User := 'test@emailarchitect.net';
        oServer.Password := 'testpassword';
        oServer.Protocol := MailServerPop3;

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

        // Set 995 SSL Port
        oServer.Port := 995;

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

        // Quit and purge emails marked as deleted from POP3 server
        oClient.Quit;

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

end.

[Delphi Example - Retrieve email from IMAP4 server over SSL on 993 port]

The following example codes demonstrate how to retrieve emails from IMAP4 server over SSL connection on 993 port. 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 := 'imap.emailarchitect.net';
        oServer.User := 'test@emailarchitect.net';
        oServer.Password := 'testpassword';
        oServer.Protocol := MailServerImap4;

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

        // Set 993 IMAP4 SSL Port
        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.

Next Section

At next section I will introduce how to download emails from Gmail account.

Appendix

Comments

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