C# - Fetch POP3 emails

By , 7/30/2013
(1 ratings)
A (simplified) snippet that shows how to fetch POP3 emails using C#.

Simply create a MailProvider object, hand over the access data and receive the Mail objects with the help of MailProvider.GetMails().

Author: Curry, translation by Michael List
// Mail.cs
namespace Tools
{
    /// <summary>
    /// Represents an email
    /// </summary>
    public class Mail
    {
        #region Vars
        private string mSenderMail;
        private string mReceiverMail;
        private string mTitle;
        private string mContent;
        #endregion

        #region Properties
        /// <summary>
        /// Sender's email adress
        /// </summary>
        public string SenderMail
        {
            get { return mSenderMail; }
            set { mSenderMail = value; }
        }
        /// <summary>
        /// Receiver's email address
        /// </summary>
        public string ReceiverMail
        {
            get { return mReceiverMail; }
            set { mReceiverMail = value; }
        }
        /// <summary>
        /// Subject
        /// </summary>
        public string Title
        {
            get { return mTitle; }
            set { mTitle = value; }
        }
        /// <summary>
        /// Content
        /// </summary>
        public string Content
        {
            get { return mContent; }
            set { mContent = value; }
        }
        #endregion
    }
}


// MailProvider.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Text;

namespace Tools
{
    /// <summary>
    /// Provides a MailProvider that is able to fetch the emails.
    /// </summary>
    public class MailProvider
    {
        #region Vars
        private NetworkStream mPop3Stream;
        private StreamReader mStreamListener;
        private byte[] mCommandBuffer = new byte[1024];
        ASCIIEncoding mAscEncoding = new ASCIIEncoding();
        private string mPopServer;
        private int mPort;
        private string mUser;
        private string mPassword;
        #endregion

        #region Properties
        /// <summary>
        /// POP3 server
        /// </summary>
        public string PopServer
        {
            get { return mPopServer; }
            set { mPopServer = value; }
        }
        /// <summary>
        /// Server port
        /// </summary>
        public int Port
        {
            get { return mPort; }
            set { mPort = value; }
        }
        /// <summary>
        /// User name
        /// </summary>
        public string User
        {
            get { return mUser; }
            set { mUser = value; }
        }
        /// <summary>
        /// Password
        /// </summary>
        public string Password
        {
            set { mPassword = value; }
        }
        #endregion

        #region Ctor
        /// <summary>
        /// Initializes a new MailProvider that is able to receive emails.
        /// </summary>
        public MailProvider(string popServer, int port, string user, string pw)
        {
            // Assign access information
            mPopServer = popServer;
            mPort = port;
            mUser = user;
            mPassword = pw;

            // Establish connection to server
            establishConnection();
        }
        #endregion

        #region Private methods
        /// <summary>
        /// Establishes a connection to the POP3 server.
        /// </summary>
        private void establishConnection()
        {
            TcpClient server = new TcpClient();

            // Establish connection
            server.Connect(this.PopServer, this.Port);

            // Initiate streams
            mPop3Stream = server.GetStream();
            mStreamListener = new StreamReader(mPop3Stream);

            // If successfully connected
            if (server.Connected)
            {
                mStreamListener.ReadLine();

                // Login
                mCommandBuffer = mAscEncoding.GetBytes(String.Format("USER {0}\r\n", this.User));
                mPop3Stream.Write(mCommandBuffer, 0, mCommandBuffer.Length);
                mStreamListener.ReadLine();
                mCommandBuffer = mAscEncoding.GetBytes(String.Format("PASS {0}\r\n", mPassword));
                mPop3Stream.Write(mCommandBuffer, 0, mCommandBuffer.Length);
                mStreamListener.ReadLine();
            }
        }
        /// <summary>
        /// Parses a Mail object using the handed over string
        /// </summary>
        private Mail parseMail(string input)
        {
            Mail retVal = null;

            // Split email into 2 halfs (header and body)
            string[] emailSplit = input.Split(new string[] { "\r\n\r\n" }, StringSplitOptions.None);
            string header = String.Empty;
            string body = String.Empty;

            if (emailSplit.Length >= 2)
            {
                // Header
                header = emailSplit[0];
                // Body
                for (int i = 1; i < emailSplit.Length - 1; i++) body = String.Concat(body, "\r\n\r\n" ,emailSplit[i]);
            }

            // Filter header information
            retVal = getHeaderInformations(header);

            // Assign content
            retVal.Content = body;

            // Return Mail object
            return retVal;
        }
        /// <summary>
        /// Returns the header informations.
        /// </summary>
        private Mail getHeaderInformations(string header)
        {
            Mail retVal = new Mail();

            // Parse every single line
            foreach (string line in header.Split(new string[] { "\r\n" }, StringSplitOptions.None))
            {
                // Split into key and value
                string[] lineSplit = line.Split(new string[] { ": " }, StringSplitOptions.None);
                string key = String.Empty;
                string value = String.Empty;

                if (lineSplit.Length >= 2)
                {
                    // Key
                    key = lineSplit[0];
                    // Value
                    for (int i = 1; i < lineSplit.Length; i++) value = String.Concat(value, lineSplit[i]);
                }

                // Assign corresponding values depending on the key
                switch (key)
                {
                    // Sender
                    case "From":
                        retVal.SenderMail = value;
                        break;
                    // Receiver
                    case "To":
                        retVal.ReceiverMail = value;
                        break;
                    // Subject
                    case "Subject":
                        retVal.Title = value;
                        break;
                }
            }

            return retVal;
        }
        #endregion

        #region Public methods
        /// <summary>
        /// Returns all emails.
        /// </summary>
        public List<Mail> GetMails()
        {
            List<Mail> retVal = new List<Mail>();
            List<string> mailList = new List<string>();

            // Request list containing all emails
            mCommandBuffer = mAscEncoding.GetBytes("LIST\r\n");
            mPop3Stream.Write(mCommandBuffer, 0, mCommandBuffer.Length);
            mStreamListener.ReadLine();

            // As long as "." is not being readed,
            // some emails are still on the server.
            string currMsg = mStreamListener.ReadLine();
            while (currMsg != ".")
            {
                mailList.Add(currMsg);
                currMsg = mStreamListener.ReadLine();
            }

            // Iterate email list
            foreach (string listVal in mailList)
            {
                Mail mail = null;

                // Filter mail index
                int mailNr = -1;
                try
                {
                    mailNr = Convert.ToInt32(listVal.Split(' ')[0]);
                }
                catch { }

                // If mail index was found, retrieve complete content
                if (mailNr != -1)
                {
                    mCommandBuffer = mAscEncoding.GetBytes(String.Format("RETR {0}\r\n",
                        mailNr));
                    mPop3Stream.Write(mCommandBuffer, 0, mCommandBuffer.Length);
                    StringBuilder mailContent = new StringBuilder();

                    // As long as "." is not being readed, the email is not completed yet
                    string tmpLine = mStreamListener.ReadLine();
                    while (tmpLine != ".")
                    {
                        mailContent.AppendLine(tmpLine);
                        tmpLine = mStreamListener.ReadLine();
                    }

                    // Parse email
                    mail = parseMail(mailContent.ToString());
                }

                if (mail != null)
                    retVal.Add(mail);
            }

            return retVal;
        }
        #endregion
    }
}
Tagged with mail, email, pop, pop3.

Comments

 

Log in, to comment!