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

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

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

[VB 6.0 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.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "imap4.emailarchitect.net"
    oServer.User = "test@emailarchitect.net"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerImap4

    ' Set IMAP4 port
    oServer.Port = 143

    ' If your IMAP4 requires SSL connection
    ' Please add the following codes
    ' oServer.SSLConnection = True
    ' oServer.Port = 993

    On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim infos
    infos = oClient.GetMailInfos()
    MsgBox UBound(infos) + 1 & " emails"

    Dim i As Integer
    For i = LBound(infos) To UBound(infos)
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos(i)
        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        Dim fileName As String

        ' Using IMAP UIDL as the file name.
        fileName = mailbox & "\" & info.UIDL & ".eml"
        If oTools.ExistFile(fileName) Then
            ' This email has been downloaded, do not receive it again.
        Else

            ' Receive email from POP3 server
            Dim oMail As EAGetMailObjLib.Mail
            Set oMail = oClient.GetMail(info)

            MsgBox "From: " & oMail.From.Address & _
                vbCrLf & "Subject: " & oMail.Subject

            ' Save email to local disk
            oMail.SaveAs fileName, True
        End If

        ' Do not delete email from IMAP4 server.
    Next

    ' Quit and purge emails marked as deleted from IMAP4 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

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.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3

Private m_uidlfile As String
Private m_uidls As String

Private oTools As New EAGetMailObjLib.Tools

'==========================================================================================
' 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.
'==========================================================================================
Private Sub LoadUIDL()
    m_uidls = ""
    m_uidls = oTools.ReadTextFile(m_uidlfile, 0)
End Sub

Private Sub UpdateUIDL()
    On Error GoTo ErrorHandleUpdateUIDL
    oTools.WriteTextFile m_uidlfile, m_uidls, 0
    On Error GoTo 0
    Exit Sub
ErrorHandleUpdateUIDL:
    MsgBox "Update UIDL Error: " & Err.Description
    On Error GoTo 0
End Sub

Private Sub SyncUIDL(ByRef oServer As EAGetMailObjLib.MailServer, ByRef infos)
    Dim arLocal
    Dim newuidls As String
    Dim uidlpref As String
    uidlpref = LCase(oServer.Server) & "#" & LCase(oServer.User) & " "

    arLocal = Split(m_uidls, vbCrLf)
    Dim i, Count
    For i = LBound(arLocal) To UBound(arLocal)
        Dim t As String
        Dim bRemove As Boolean
        bRemove = False
        t = arLocal(i)
        If Len(t) > Len(uidlpref) Then
            Dim curPref
            curPref = Left(t, Len(uidlpref))
            If StrComp(curPref, uidlpref, vbBinaryCompare) = 0 Then

                Dim localuidl
                localuidl = Mid(t, Len(uidlpref) + 1)

                Dim bExistOnServer As Boolean
                bExistOnServer = False

                Dim x
                For x = LBound(infos) To UBound(infos)
                    If StrComp(infos(x).UIDL, localuidl, vbBinaryCompare) = 0 Then
                        bExistOnServer = True
                    Exit For
                    End If
                Next
                If Not bExistOnServer Then
                    bRemove = True
                End If
            End If
        End If

        If Trim(t) = "" Then
            bRemove = True
        End If

        If Not bRemove Then
            newuidls = newuidls & t & vbCrLf
        End If
    Next

    m_uidls = newuidls
End Sub

Private Function FindExistedUIDL(ByRef oServer As EAGetMailObjLib.MailServer, _
        ByRef UIDL As String) As Boolean
        Dim s As String
        s = LCase(oServer.Server) & "#" & LCase(oServer.User) & " " & UIDL & vbCrLf
        If InStr(1, m_uidls, s, vbBinaryCompare) > 0 Then
            FindExistedUIDL = True
        Else
            FindExistedUIDL = False
        End If
End Function

Private Sub AddUIDL(ByRef oServer As EAGetMailObjLib.MailServer, ByRef UIDL As String)
        Dim s As String
        s = LCase(oServer.Server) & "#" & LCase(oServer.User) & " " & UIDL & vbCrLf
        m_uidls = m_uidls & s
End Sub

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    m_uidlfile = curpath & "\uidl.txt"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "pop3.emailarchitect.net"
    oServer.User = "test@emailarchitect.net"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerPop3

    ' If your POP3 requires SSL connection
    ' Please add the following codes
    ' oServer.SSLConnection = True
    ' oServer.Port = 995

    On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

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

    Dim infos
    infos = oClient.GetMailInfos()
    MsgBox UBound(infos) + 1 & " emails"

    SyncUIDL oServer, infos

    Dim i As Integer
    For i = LBound(infos) To UBound(infos)
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos(i)
        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' If this email has not been downloaded before, then get it
        If Not FindExistedUIDL(oServer, info.UIDL) Then

            ' Receive email from POP3 server
            Dim oMail As EAGetMailObjLib.Mail
            Set oMail = oClient.GetMail(info)

            MsgBox "From: " & oMail.From.Address & _
                vbCrLf & "Subject: " & oMail.Subject

            Dim fileName As String
            ' 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 = mailbox & "\" & oTools.GenFileName(i) & ".eml"

            ' Save email to local disk
            oMail.SaveAs fileName, True

            ' Add the email uidl to uidl file to avoid we retrieve it next time.
            AddUIDL oServer, info.UIDL
            ' Do not delete the email
        End If
    Next

    ' Quit
    oClient.Quit

    ' Update the uidl list to a text file and then we can load it next time.
    UpdateUIDL
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
    ' Update the uidl list to a text file and then we can load it next time.
    UpdateUIDL
End Sub

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.

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.