Using UIDL Function to Mark the Email has been downloaded/read in Delphi

In previous section, I introduced how to use event handler. In this section, I will introduce how to use UIDL function to mark the email has been downloaded in Delphi.

Introduction

If you want to leave a copy of email on the server, you should not call Delete method. However, there is a problem, how can you know if the email has already been downloaded? If there is a way to identify the downloaded email, you can avoid downloading the duplicated email from your POP3/IMAP4 server.

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

Every email has a unique identifier (UIDL) on IMAP4 server. It is a 32bit integer and it is always unique in your email account life time. So we can use the integer as file name to identify if the email has been downloaded. In order to run it correctly, please change email server, user, password, folder, file name values.

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]));

                // Using IMAP UIDL as the file name
                fileName := localInbox + '\' + oInfo.UIDL + '.eml';

                if oTools.ExistFile(fileName) then
                    continue; // this email has been downloaded, do not receive it again.

                // 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);

                // Do not delete email
            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.

POP3/IMAP4/Exchange Web Service/WebDAV Solution

There is a little bit different in POP3 server. The UIDL is only unique in the email life time. That means if the email was deleted from the server, other email can use the old unique identifier. Another problem is: UIDL in POP3 server can be any number or characters, so we cannot use UIDL as the file name, because UIDL may contain invalid characters for file name.

UIDL is also unique in Exchange Web Service/WebDAV, but the UIDL is string but not integer. UIDL in Exchange server may contain invalid characters for file name, so we cannot use UIDL as the file name either.

To solve this problem, we have to store the UIDL to a txt file and synchronize it with server every time.

Please have a look at the following example code. It works with both POP3/IMAP4/Exchange Web Service/WebDAV protocol.

unit Unit1;

interface

uses
    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
    Dialogs, StdCtrls, StrUtils, 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;
    MailServerMsGraph = 4;


var
    Form1: TForm1;

implementation

{$R *.dfm}


procedure TForm1.Button1Click(Sender: TObject);
var
    oServer: TMailServer;
    oClient: TMailClient;
    oTools: TTools;
    oMail: IMail;
    oUIDLManager: TUIDLManager;
    infos: IMailInfoCollection;
    oInfo: IMailInfo;
    localInbox, fileName, fullFileName: WideString;
    isUidlLoaded: Boolean;
    leaveCopy: Boolean;
    i: integer;
begin
    // set current thread code page to system default code page.
    SetThreadLocale(GetSystemDefaultLCID());

    // leave a copy of message on server
    leaveCopy := true;
    isUidlLoaded := false;

    // uidl is the identifier of every email on POP3/IMAP4 server, to avoid retrieve
    // the same email from server more than once, we record the email uidl retrieved every time
    // if you delete the email from server every time and not to leave a copy of email on
    // the server, then please remove all the function about uidl.
    oUIDLManager := TUIDLManager.Create(Application);

    try
        oTools := TTools.Create(Application);
        localInbox := GetCurrentDir() + '\inbox';
        oTools.CreateFolder(localInbox);

        oUIDLManager.Load(localInbox + '\uidl.txt');
        isUidlLoaded := true;

        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';

        oClient.Connect1(oServer.DefaultInterface);
        ShowMessage( 'Connected!' );

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

        // Remove the local uidl that is not existed on the server,
        oUIDLManager.SyncUIDLEX(oServer.DefaultInterface, infos);
        oUIDLManager.Update();

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

                // This email has not been retrieved before, then get it
                if oUIDLManager.FindUIDL(oServer.DefaultInterface, oInfo.UIDL) <> nil then
                    continue; // this email has been downloaded, do not receive it again

                // 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 := oTools.GenFileName(i) + '.eml';
                fullFileName := localInbox + '\' + fileName;

                // Receive email from email server
                oMail := oClient.GetMail(oInfo);

                ShowMessage('From: ' + oMail.From.Address + #13#10 +
                    'Subject: ' + oMail.Subject);

                // Save email to local disk
                oMail.SaveAs(fullFileName, true);

                if leaveCopy Then
                    begin
                        // Add the email uidl to uidl file to avoid we retrieve it next time.
                        oUIDLManager.AddUIDL(oServer.DefaultInterface, oInfo.UIDL, fileName);
                    end
                else
                    begin
                        oClient.Delete(oInfo);

                        // Remove UIDL from local uidl file.
                        oUIDLManager.RemoveUIDL(oServer.DefaultInterface, oInfo.UIDL);
                    end;

            end;
        // Quit and expunge emails marked as deleted from email server
        oClient.Quit;

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

    // Update the uidl list to a text file and then we can load it next time.
    if isUidlLoaded then
        oUIDLManager.Update();

end;

end.

UIDLManager Object

With EAGetMail 4.0, it provides a new class named “UIDLManager”. This object provides an easy way to maintain UIDL between your server and your local client. How does it work? It stores UIDL collection to a local disk file and you can use this object to add, remove and search UIDL with this local file. Then you don’t have to handle UIDL in your code. Please click here to learn more detail.

Mark Email as Read on IMAP4/Exchange Server

With IMAP4/Exchange Web Service/WebDAV protocol, you can also mark the email as read on the server, but POP3 doesn’t support this feature. Please refer to MarkAsRead method to learn more detail.

Delphi - Retrieve Unread/New Email in IMAP4/EWS/WebDAV

Because IMAP/EWS/WebDAV support read mail flag, with this feature, we can also retrieve unread/new email only from IMAP4/EWS/WebDAV like this

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;


    // GetMailInfosParam Flags
    GetMailInfos_All = 1;
    GetMailInfos_NewOnly = 2;
    GetMailInfos_ReadOnly = 4;
    GetMailInfos_SeqRange = 8;
    GetMailInfos_UIDRange = 16;
    GetMailInfos_PR_ENTRYID = 32;
    GetMailInfos_DateRange = 64;
    GetMailInfos_OrderByDateTime = 128;

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

        // Enable SSL/TLS Connection, most modern email server require SSL/TLS connection by default.
        oServer.SSLConnection := true;
        // Set 993 SSL IMAP4 port
        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!');

        // retrieve unread/new email only
        oClient.GetMailInfosParam.Reset();
        oClient.GetMailInfosParam.GetMailInfosOptions := GetMailInfos_NewOnly;

        infos := oClient.GetMailInfoList();
        ShowMessage(Format('Total %d unread 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 unread email as read, next time this email won't be retrieved again
                if not oInfo.Read then
                    oClient.MarkAsRead(oInfo, true);

                // if you don't want to leave a copy on server, please use
                //  oClient.Delete(oInfo);
                // instead of MarkAsRead
            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.

Next Section

At next section I will introduce how to download email in background.

Appendix

Comments

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