Managed C++/CLI - 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++/CLI 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.

Install from NuGet

You can also install the run-time assembly by NuGet. Run the following command in the NuGet Package Manager Console:

Install-Package EAGetMail

Note

If you install it by NuGet, no sample projects are installed, only .NET assembly is installed.

Add Reference

To use EAGetMail POP3 & IMAP Component in your project, the first step is “Add reference of EAGetMail to your project”. Please create or open your project with Visual Studio, then go to menu -> Project -> Add Reference -> .NET -> Browse..., and select EAGetMail{version}.dll from installation path, click Open-> OK, the reference will be added to the project, you can start to use it to retrieve email and parse email in your project.

add reference in c#/vb.net/managed c++/cli

.NET Assembly

Because EAGetMail has separate builds for .Net Framework, please refer to the following table and choose the correct dll.

Separate builds of run-time assembly for .Net Framework 1.1, 2.0, 3.5, 4.0, 4.5 and .Net Compact Framework 2.0, 3.5.

File .NET Framework Version
EAGetMail.dll Built with .NET Framework 1.1
It requires .NET Framework 1.1, 2.0, 3.5 or later version.
EAGetMail20.dll Built with .NET Framework 2.0
It requires .NET Framework 2.0, 3.5 or later version.
EAGetMail35.dll Built with .NET Framework 3.5
It requires .NET Framework 3.5 or later version.
EAGetMail40.dll Built with .NET Framework 4.0
It requires .NET Framework 4.0 or later version.
EAGetMail45.dll Built with .NET Framework 4.5
It requires .NET Framework 4.5 or later version.
EAGetMailCF20.dll Built with .NET Compact Framework 2.0
It requires .NET Compact Framework 2.0, 3.5 or later version.
EAGetMailCF35.dll Built with .NET Compact Framework 3.5
It requires .NET Compact Framework 3.5 or later version.

Managed C++/CLI - 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"

using namespace System;
using namespace System::Text;
using namespace System::Collections;
using namespace System::IO;

// Add EAGetMail namespace
using namespace EAGetMail;

public ref class MyMailClient
{
private: String ^m_uidlfile;
private: String ^m_curpath;
private: ArrayList ^m_arUidl;
// UIDL Functions
// 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: bool _FindUIDL(array<MailInfo^>^ infos, String ^uidl)
{
    int count = infos->Length;
    for(int i = 0; i < count; i++)
    {
        if(String::Compare(infos[i]->UIDL, uidl, false) == 0)
            return true;
    }
    return false;
}

// Remove the local uidl which is not existed on the server.
private: void _SyncUIDL(MailServer ^oServer, array<MailInfo^>^ infos)
{
    String ^s = String::Format("{0}#{1} ", oServer->Server, oServer->User);

    bool bcontinue = false;
    int n = 0;
    do
    {
        bcontinue = false;
        int count = m_arUidl->Count;
        for(int i = n; i < count; i++)
        {
            String ^x = dynamic_cast<String^>(m_arUidl[i]);
            if(String::Compare(s, 0, x, 0, s->Length, true) == 0)
            {
                int pos = x->LastIndexOf(' ');
                if(pos != -1)
                {
                    String ^uidl = x->Substring(pos + 1);
                    if(!_FindUIDL(infos, uidl))
                    {
                        // This uidl doesn't exist on server,
                        // so we should remove it from local uidl list.
                        bcontinue = true;
                        n = i;
                        m_arUidl->RemoveAt(i);
                        break;
                    }
                }
            }
        }
    }while(bcontinue);

}

private: bool _FindExistedUIDL(MailServer ^oServer, String ^uidl)
{
    String ^s = String::Format("{0}#{1} {2}",
        oServer->Server->ToLower(), oServer->User->ToLower(), uidl);
    int count = m_arUidl->Count;
    for(int i = 0; i < count; i++)
    {
        String ^x = dynamic_cast<String^>(m_arUidl[i]);
        if(String::Compare(s, x, false) == 0)
            return true;
    }
    return false;
}

private: void _AddUIDL(MailServer ^oServer, String ^uidl)
{
    String ^s = String::Format("{0}#{1} {2}",
        oServer->Server->ToLower(), oServer->User->ToLower(), uidl);
    m_arUidl->Add(s);
}

private: void _UpdateUIDL()
{
    StringBuilder ^s = gcnew StringBuilder();
    int count = m_arUidl->Count;
    for(int i = 0; i < count; i++)
    {
        s->Append(dynamic_cast<String^>(m_arUidl[i]));
        s->Append("\r\n");
    }

    String ^file = String::Format("{0}\\{1}", m_curpath, m_uidlfile);

    FileStream ^fs = nullptr;
    try
    {
        fs = gcnew FileStream(file, FileMode::Create, FileAccess::Write, FileShare::None);
        array<unsigned char>^ data = System::Text::Encoding::Default->GetBytes(s->ToString());
        fs->Write(data, 0, data->Length);
        fs->Close();
    }
    catch(Exception ^ep)
    {
        if(fs != nullptr)
            fs->Close();

        throw ep;
    }

}

private: void _LoadUIDL()
{
    m_arUidl->Clear();
    String ^file = String::Format("{0}\\{1}", m_curpath, m_uidlfile);
    StreamReader ^read = nullptr;
    try
    {
        read = File::OpenText(file);
        while(true)
        {
            String ^strim = "\r\n \t";
            String ^line = read->ReadLine()->Trim(strim->ToCharArray());
            m_arUidl->Add(line);
        }
    }
    catch(Exception ^ep)
    {}

    if(read != nullptr)
        read->Close();
}

public: void ReceiveEmail(MailServer ^oServer, bool bLeaveCopy)
{
    m_arUidl = gcnew ArrayList();
    m_uidlfile = "uidl.txt";
    MailClient ^oClient = gcnew MailClient("TryIt");
    m_curpath = Directory::GetCurrentDirectory();
    try
    {
    // 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();

        String ^mailFolder = String::Format("{0}\\inbox", m_curpath);
        if (!Directory::Exists(mailFolder))
            Directory::CreateDirectory(mailFolder);

        Console::WriteLine("Connecting server ... ");
        oClient->Connect(oServer);
        array<MailInfo^> ^infos = oClient->GetMailInfos();
        Console::WriteLine("Total {0} email(s)", infos->Length);

        _SyncUIDL(oServer, infos);
        int count = infos->Length;

        for (int i = 0; i < count; i++)
        {
            MailInfo ^info = infos[i];
            if (_FindExistedUIDL(oServer, info->UIDL))
            {
                // This email has existed on local disk.
                continue;
            }

            Console::WriteLine("Retrieving {0}/{1}...", info->Index, count);

            Mail ^oMail = oClient->GetMail(info);
            System::DateTime d = System::DateTime::Now;
            System::Globalization::CultureInfo ^cur =
                gcnew System::Globalization::CultureInfo("en-US");
            String ^sdate = d.ToString("yyyyMMddHHmmss", cur);
            String ^fileName = String::Format("{0}\\{1}{2}{3}.eml",
                    mailFolder, sdate, d.Millisecond.ToString("d3"), i);
            oMail->SaveAs(fileName, true);

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

        if (!bLeaveCopy)
        {
            Console::WriteLine("Deleting ...");
            for (int i = 0; i < count; i++)
                oClient->Delete(infos[i]);
        }

        Console::WriteLine("Completed");
        // Delete method just mark the email as deleted,
        // Quit method purge the emails from server exactly.
        oClient->Quit();

    }
    catch (Exception ^ep)
    {
        Console::WriteLine(ep->Message);
    }

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

};

int main(array<System::String ^> ^args)
{
    // Create a folder named "inbox" under current directory
    // to save the email retrieved.
    String ^curpath = Directory::GetCurrentDirectory();
    String ^mailbox = String::Format("{0}\\inbox", curpath);

    // If the folder is not existed, create it.
    if (!Directory::Exists(mailbox))
    {
        Directory::CreateDirectory(mailbox);
    }

    MailServer ^oServer = gcnew MailServer("pop3.emailarchitect.net",
        "test@emailarchitect.net", "testpassword", ServerProtocol::Pop3);
    MailClient ^oClient = gcnew MailClient("TryIt");

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

    MyMailClient ^MyClient = gcnew MyMailClient();
    MyClient->ReceiveEmail(oServer, true);

    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

Appendix

Comments

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