Retrieve Email with Event Handler in Delphi

In previous section, I introduced how to retrieve email from Hotmail/MSN Live account. In this section, I will introduce how to retrieve email with event handler in Delphi.

Introduction

After Connect method, GetMail method or other methods are invoked, if you want to know the progress of the email receiving, you should use Event Handler. The following sample codes demonstrate how to use Event Handler to monitor the progress of email receiving.

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 with event handler]

The following example codes demonstrate how to use EAGetMail POP3 component to retrieve email with event handler. In order to run it correctly, please change email server, user, password, folder, file name values.

Please add a TLable control named Label1.

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;
        Label1: TLabel;
        procedure Button1Click(Sender: TObject);
    private
        { Private declarations }
        // EAGetMail event handler
        procedure OnIdle(ASender: TObject; const oSender: IDispatch; var Cancel: WordBool);
        procedure OnConnected(ASender: TObject; const oSender: IDispatch; var Cancel: WordBool);
        procedure OnQuit(ASender: TObject; const oSender: IDispatch; var Cancel: WordBool);
        procedure OnSecuring(ASender: TObject; const oSender: IDispatch; var Cancel: WordBool);
        procedure OnAuthorized(ASender: TObject; const oSender: IDispatch;
        var Cancel: WordBool);
        procedure OnSendingDataStream(ASender: TObject; const oSender: IDispatch;
        Sent: Integer; Total: Integer;
        var Cancel: WordBool);
        procedure OnReceivingDataStream(ASender: TObject; const oSender: IDispatch;
        const oInfo: IDispatch;
        Received: Integer; Total: Integer;
        var Cancel: WordBool);
    public
        { Public declarations }
    end;

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

var
    Form1: TForm1;

implementation

{$R *.dfm}

// EAGetMail event handler
procedure TForm1.OnIdle(ASender: TObject; const oSender: IDispatch; var Cancel: WordBool);
begin
    Application.ProcessMessages();
end;

procedure TForm1.OnConnected(ASender: TObject; const oSender: IDispatch; var Cancel: WordBool);
begin
    Label1.Caption := 'Connected';
end;

procedure TForm1.OnQuit(ASender: TObject; const oSender: IDispatch; var Cancel: WordBool);
begin
    Label1.Caption := 'Disconnecting ...';
end;

procedure TForm1.OnSecuring(ASender: TObject; const oSender: IDispatch; var Cancel: WordBool);
begin
    Label1.Caption := 'Securing ...';
end;

procedure TForm1.OnAuthorized(ASender: TObject; const oSender: IDispatch;
    var Cancel: WordBool);
begin
    Label1.Caption := 'Authorized';
end;

procedure TForm1.OnSendingDataStream(ASender: TObject; const oSender: IDispatch;
    Sent: Integer; Total: Integer;
    var Cancel: WordBool);
begin
    //implementation code for IMAP4 appending event
end;

procedure TForm1.OnReceivingDataStream(ASender: TObject; const oSender: IDispatch;
    const oInfo: IDispatch;
    Received: Integer; Total: Integer;
    var Cancel: WordBool);
var
    info: IMailInfo;
begin
    info := oInfo as IMailInfo;
    Label1.Caption := Format( 'Receiving %d, %d/%d ...',
        [info.Index, Received, Total]);
end;

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

        // Enable SSL/TLS Connection, most modern email server require SSL/TLS connection by default.
        oServer.SSLConnection := true;
        // Set 995 SSL POP3 port
        oServer.Port := 995;

        // If your POP3 server doesn't deploy SSL connection
        // Please use
        // oServer.SSLConnection := false;
        // oServer.Port := 110;

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

        // Add eagetmail event handler
        oClient.OnIdle := OnIdle;
        oClient.OnConnected := OnConnected;
        oClient.OnQuit := OnQuit;
        oClient.OnSecuring := OnSecuring;
        oClient.OnAuthorized := OnAuthorized;
        oClient.OnSendingDataStream := OnSendingDataStream;
        oClient.OnReceivingDataStream := OnReceivingDataStream;

        Label1.Caption := 'Connecting ...';

        oClient.Connect1(oServer.DefaultInterface);
        Label1.Caption := 'Connected!';

        infos := oClient.GetMailInfoList();
        Label1.Caption := Format('Total %d email(s)', [infos.Count]);

        for i := 0 to infos.Count - 1 do
            begin
                oInfo := infos.Item[i];

                Label1.Caption := 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 POP3 server
                oMail := oClient.GetMail(oInfo);

                Label1.Caption := '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 expunge emails marked as deleted from POP3 server
        oClient.Quit;
        Label1.Caption := 'Completed!';

    except
        on ep:Exception do
            Label1.Caption := 'Error: ' + ep.Message;
    end;


end;

end.

Next Section

At next section I will introduce how to use UIDL function to mark the email has been downloaded.

Appendix

Comments

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