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

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 C#.

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 C# 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.

[C# 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.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace

namespace receiveemail
{
    class Program
    {
        static void Main(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 = new MailServer("imap4.emailarchitect.net",
                        "test@emailarchitect.net", "testpassword", ServerProtocol.Imap4 );
            MailClient oClient = new MailClient("TryIt");

            // Set IMAP4 server port
            oServer.Port = 143;

            // If your IMAP4 server requires SSL connection,
            // Please add the following codes:
            // oServer.SSLConnection = true;
            // oServer.Port = 993;

            try
            {
                oClient.Connect(oServer);
                MailInfo[] infos = oClient.GetMailInfos();
                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info = infos[i];
                    Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
                        info.Index, info.Size, info.UIDL);

                    // Using IMAP UIDL as the file name.
                    string fileName = String.Format("{0}\\{1}.eml",
                        mailbox, info.UIDL );

                    if( File.Exists( fileName ))
                    {

                    // This email has been downloaded,  do not download it again.
                        continue;
                    }

                    // Receive email from IMAP4 server
                    Mail oMail = oClient.GetMail(info);

                    Console.WriteLine("From: {0}", oMail.From.ToString());
                    Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

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

                    // Do not delete email from IMAP4 server.
                }

                // Quit
                oClient.Quit();
            }
            catch (Exception ep)
            {
                Console.WriteLine(ep.Message);
            }

        }
    }
}

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.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace

namespace receiveemail
{
    class MyMailClient
    {
        private string m_uidlfile = "uidl.txt";
        private string m_curpath = "";
        private ArrayList m_arUidl = new ArrayList();

        #region 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(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, 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 = m_arUidl[i] as string;
                    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,
                                // remove it from local uidl list to save the storage.
                                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 = m_arUidl[i] as string;
                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 = new StringBuilder();
            int count = m_arUidl.Count;
            for (int i = 0; i < count; i++)
            {
                s.Append(m_arUidl[i] as string);
                s.Append("\r\n");
            }

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

            FileStream fs = null;
            try
            {
                fs = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None);
                byte[] data = System.Text.Encoding.Default.GetBytes(s.ToString());
                fs.Write(data, 0, data.Length);
                fs.Close();
            }
            catch (Exception ep)
            {
                if (fs != null)
                    fs.Close();

                throw ep;
            }

        }

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

            if (read != null)
                read.Close();
        }
        #endregion

        public void ReceiveEmail(MailServer oServer, bool bLeaveCopy )
        {
            MailClient oClient = new 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);
                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 =
                            new 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();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MailServer oServer = new MailServer("pop3.emailarchitect.net",
                        "test@emailarchitect.net", "testpassword", ServerProtocol.Pop3 );

            MyMailClient oMyClient = new MyMailClient();
            // Leave a copy of email on server
            oMyClient.ReceiveEmail(oServer, true);
        }
    }
}

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.