Visual C++ - Mark Email as Read in POP3

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 (read)? If there is a way to identify the downloaded email, you can avoid downloading the duplicated email from your POP3/IMAP4 server.

Every email has a unique identifier (UIDL) on POP3 server. POP3 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.

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

The following c++ example codes demonstrate how to mark the email as downloaded/read on POP3 server.

Installation

Before you can use the following sample codes, you should download the EAGetMail Installer and install it on your machine at first. Full sample projects are included in this installer.

Add Reference

To use EAGetMail POP3 & IMAP4 ActiveX Object in your project, the first step is “Add header files of EAGetMail to your project”. Please go to C:\Program Files\EAGetMail\Samples_VS2008\pop3_imap4_simple.vcNative or C:\Program Files (x86)\EAGetMail\Samples_VS2008\pop3_imap4_simple.vcNative folder, find eagetmailobj.tlh and eagetmailobj.tli, and then copy these files to your project folder. You can start to use it to retrieve email and parse email in your project.

add reference in C++

Visual C++ - Mark Email as Read in POP3 - Example

The following example codes demonstrate marking email as read/downloaded on POP3 server. In order to run it correctly, please change email server, user, password, folder, file name value to yours.

Note

To get full sample projects, please download and install EAGetMail on your machine.

#include "stdafx.h"
#include <atlbase.h>
#include <atlcom.h>
#include <atlstr.h>

#include "eagetmailobj.tlh"
using namespace EAGetMailObjLib;

class MyClient
{
public:
    MyClient()
    {
        m_uidlfile = _T("uidl.txt");

        TCHAR szFile[MAX_PATH+1];
        memset(szFile, 0, sizeof(szFile));
        ::GetModuleFileName(NULL, szFile, MAX_PATH);
        LPCTSTR pszBuf = _tcsrchr(szFile, _T('\\'));
        if(pszBuf != NULL)
        {
            m_curpath.Append(szFile, pszBuf - szFile);
        }
        else
        {/*impossible*/
            m_curpath.Append(szFile);
        }
    }

public:
    void ReceiveMail(IMailServerPtr &oServer, bool leaveCopy)
    {
        try
        {
            CString mailFolder;
            mailFolder.Format(_T("%s\\inbox"), m_curpath.GetString());
            ::CreateDirectory(mailFolder.GetString(), NULL);

            IMailClientPtr oClient = NULL;
            oClient.CreateInstance("EAGetMailObj.MailClient");
            oClient->LicenseCode = _T("TryIt");

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

            oClient->Connect(oServer);
            _tprintf(_T("Connected\r\n"));

            _variant_t arInfo = oClient->GetMailInfos();

            _SyncUIDL(oServer, arInfo);

            SAFEARRAY *psa = arInfo.parray;

            long LBound = 0, UBound = 0;
            SafeArrayGetLBound(psa, 1, &LBound);
            SafeArrayGetUBound(psa, 1, &UBound);

            INT count = UBound-LBound+1;
            _tprintf(_T("Total %d email(s)\r\n"), count);

            for(long i = LBound; i <= UBound; i++)
            {
                _variant_t vtInfo;
                SafeArrayGetElement(psa, &i, &vtInfo);

                IMailInfoPtr pInfo;
                vtInfo.pdispVal->QueryInterface(__uuidof(IMailInfo), (void**)&pInfo);

                if(_FindExistedUIDL(oServer, pInfo->UIDL))
                {
                    // this email has been downloaded, do not retrieve it again.
                    continue;
                }

                IMailPtr oMail = oClient->GetMail(pInfo);

                // Generate an unique file named based on current date time
                // If you don't like it, you can use your method to generate file name
                CString fileName;
                SYSTEMTIME curtm;
                ::GetLocalTime(&curtm);
                fileName.Format(_T("%04d%02d%02d%02d%02d%02d%03d%d.eml"),
                    curtm.wYear,
                    curtm.wMonth,
                    curtm.wDay,
                    curtm.wHour,
                    curtm.wMinute,
                    curtm.wSecond,
                    curtm.wMilliseconds,
                    i);

                CString full = mailFolder;
                full.Append(_T("\\"));
                full.Append(fileName);
                oMail->SaveAs(full.GetString(), VARIANT_TRUE);

                oMail.Release();

                if(leaveCopy)
                {
                    // add the email uidl to uidl file to avoid we retrieve it next time.
                    _AddUIDL(oServer, pInfo->UIDL);
                }
            }

            if(!leaveCopy)
            {
                _tprintf(_T("Deleting ..."));
                for(long i = LBound; i <= UBound; i++)
                {
                    _variant_t vtInfo;
                    SafeArrayGetElement(psa, &i, &vtInfo);

                    IMailInfoPtr pInfo;
                    vtInfo.pdispVal->QueryInterface(__uuidof(IMailInfo), (void**)&pInfo);
                    oClient->Delete(pInfo);
                }
            }

            // Delete method just mark the email as deleted,
            // Quit method purge the emails from server exactly.
            arInfo.Clear();
            oClient->Quit();
            _tprintf(_T("Completed"));
        }
        catch(_com_error &ep)
        {
            _tprintf(_T("Error: %s\r\n"), (const TCHAR*)ep.Description());
        }

        //update the uidl list to a text file and then we can load it next time.
        _UpdateUIDL();
    }

private:
// 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.
    bool _FindUIDL(_variant_t &infos, LPCTSTR lpszUidl)
    {
        SAFEARRAY *psa = infos.parray;
        long LBound = 0, UBound = 0;
        SafeArrayGetLBound(psa, 1, &LBound);
        SafeArrayGetUBound(psa, 1, &UBound);

        for(long i = LBound; i <= UBound; i++)
        {
            IMailInfoPtr pInfo;
            _variant_t vtInfo;
            SafeArrayGetElement(psa, &i, &vtInfo);
            vtInfo.pdispVal->QueryInterface(__uuidof(IMailInfo), (void**)&pInfo);
            INT t = _tcscmp(pInfo->UIDL, lpszUidl);
            if(t == 0)
            {
                return true;
            }
        }

        return false;
    }

    void _SyncUIDL(IMailServerPtr &oServer, _variant_t &infos)
    {
        CString s;
        s = (TCHAR*)oServer->Server;
        s += _T("#");
        s += (TCHAR*)oServer->User;
        s += _T(" ");
        s = s.MakeLower();
        bool bcontinue = false;
        int n = 0;
        do
        {
            bcontinue = false;
            int count = m_arUidl.GetSize();
            for(int i = n; i < count; i++)
            {
                CString x = m_arUidl[i];
                if(_tcsncmp(x.GetString(), s.GetString(), s.GetLength()) == 0)
                {
                    int pos = x.ReverseFind(_T(' '));
                    if(pos != -1)
                    {
                        CString uidl;
                        uidl = x.Mid(pos + 1);
                        if(!_FindUIDL(infos, uidl.GetString()))
                        {
                            // this uidl doesn't exist on server,
                            // so we should remove it from local uidl list to save the storage.
                            bcontinue = true;
                            n = i;
                            m_arUidl.RemoveAt(i);
                            break;
                        }
                    }
                }
            }
        }while(bcontinue);
    }

    bool _FindExistedUIDL(IMailServerPtr &oServer, LPCTSTR lpszUidl)
    {
        CString s;
        s = (TCHAR*)oServer->Server;
        s += _T("#");
        s += (TCHAR*)oServer->User;
        s += _T(" ");
        s = s.MakeLower();
        s += lpszUidl;

        int count = m_arUidl.GetSize();
        for(int i = 0; i < count; i++)
        {
            CString x = m_arUidl[i];
            if(x.Compare(s) == 0)
                return true;
        }
        return false;
    }
    void _AddUIDL(IMailServerPtr &oServer, LPCTSTR lpszUidl)
    {
        CString s;
        s = (TCHAR*)oServer->Server;
        s += _T("#");
        s += (TCHAR*)oServer->User;
        s = s.MakeLower();
        s += _T(" ");
        s += lpszUidl;
        m_arUidl.Add(s);
    }

    void _UpdateUIDL()
    {
        CString s;
        int count = m_arUidl.GetSize();
        s.Preallocate(count * 256);

        for(int i = 0; i < count; i++)
        {
            s.Append(m_arUidl[i]);
            s.Append(_T("\r\n"));
        }

        CString file;
        file.Format(_T("%s\\%s"), m_curpath.GetString(), m_uidlfile.GetString());

        IToolsPtr oTool;
        oTool.CreateInstance("EAGetMailObj.Tools");
        oTool->WriteTextFile(file.GetString(), s.GetString(), CP_UTF8);
        oTool.Release();
    }

    void _LoadUIDL()
    {
        m_arUidl.RemoveAll();

        IToolsPtr oTool;
        oTool.CreateInstance("EAGetMailObj.Tools");
        CString file;
        file.Format(_T("%s\\%s"), m_curpath.GetString(), m_uidlfile.GetString());

        CString s;
        try
        {
            s = (TCHAR*)oTool->ReadTextFile(file.GetString(), CP_UTF8);
        }
        catch(_com_error &ep)
        {
        }

        oTool.Release();

        int curPos = 0;
        CString resToken= s.Tokenize(_T("\n"),curPos);
        while (resToken != _T(""))
        {
            resToken = resToken.Trim(_T("\r\n \t"));
            if(resToken.GetLength() > 0)
            {
                m_arUidl.Add(resToken);
            }
            resToken = s.Tokenize(_T("\n"), curPos);
        }
    }

    CString m_uidlfile;
    CString m_curpath;
    CSimpleArray<CString> m_arUidl;
};

int _tmain(int argc, _TCHAR* argv[])
{
    const int MailServerPop3 = 0;
    const int MailServerImap4 = 1;

    // Initialize COM environment
    ::CoInitialize(NULL);

    // Create a folder named "inbox" under current exe file directory
    // to save the emails retrieved.
    TCHAR szPath[MAX_PATH+1];
    memset(szPath, 0, sizeof(szPath));
    ::GetModuleFileName(NULL, szPath, MAX_PATH);

    // Change file name to current full path
    LPCTSTR psz = _tcsrchr(szPath, _T('\\'));
    if(psz != NULL)
    {
        szPath[psz-szPath] = _T('\0');
    }
    TCHAR szMailBox[MAX_PATH+1];
    memset(szMailBox, 0, sizeof(szMailBox));
    wsprintf(szMailBox, _T("%s\\inbox"), szPath);

    // Create a folder to store emails
    ::CreateDirectory(szMailBox, NULL);

    try
    {
        IMailServerPtr oServer = NULL;
        oServer.CreateInstance("EAGetMailObj.MailServer");
        oServer->Server = _T("pop3.emailarchitect.net");
        oServer->User = _T("test@emailarchitect.net");
        oServer->Password = _T("testpassword");
        oServer->Protocol = MailServerPop3;

        // If your POP3 requires SSL connection
        // Please add the following codes
        // oServer->SSLConnection = VARIANT_TRUE;
        // oServer->Port = 995;

        MyClient client;
        client.ReceiveMail(oServer, true);

    }
    catch(_com_error &ep)
    {
        _tprintf(_T("Error: %s"), (const TCHAR*)ep.Description());
    }

    return 0;
}

UIDL Manager

UIDLManager provides an easier way to maintain UIDL between your server and your local client. 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.

Work with UIDL Manager

32bit/x64 ActiveX DLL

Seperate builds of run-time dll for 32 and x64 platform

File Platform
Installation Path\EAGetMailObj.dll 32 bit
Installation Path\x64\EAGetMailObj.dll 64 bit

Distribution

  • Standard EXE

    For VB6, C++, Delphi or other standard exe application, you can distribute EAGetMailObj.dll with your application to target machine without COM-registration and installer. To learn more detail, please have a look at Registration-free COM with Manifest File.

  • Script

    For ASP, VBScript, VBA, MS SQL Stored Procedure, you need to install EAGetMail on target machine by EAGetMail installer, both 32bit/x64 DLL are installed and registered.

Appendix

Comments

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