A day with .Net

My day to day experince in .net

POP3 client using c#

Posted by vivekcek on June 14, 2011

Hi Friends,

This time i am coming with a very small solution for POP3 mail download from mail services like gmail,yahoo etc.Our client was an aggressive guy who need an application to download mail from his mail server and store these mails and attachments into a database table.The time given was 24 hours.After some Google search we decided to use OpenPop.NET an open source library.You can download it from http://hpop.sourceforge.net/.

Below i am going to explain the basics steps to test the DLL.

1. Create a windows form application.
2. Add reference to OpenPop.NET.DLL
3. Put a button in the form and check the code behind
4. Provide your mail credentials.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using OpenPop.Mime;
using OpenPop.Mime.Header;
using OpenPop.Pop3;
using OpenPop.Pop3.Exceptions;
using OpenPop.Common.Logging;
using Message = OpenPop.Mime.Message;
namespace mailtest
{
    public partial class Form1 : Form
    {
        private Pop3Client pop3Client;
        private Dictionary<int, Message> messages;
        public Form1()
        {
            InitializeComponent();
            pop3Client = new Pop3Client();
            messages = new Dictionary<int, Message>();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ReceiveMails();
        }
        private void ReceiveMails()
        {
            try
            {
                if (pop3Client.Connected)
                    pop3Client.Disconnect();
                pop3Client.Connect("pop.gmail.com", 995, true);
                pop3Client.Authenticate("your@gmail.com", "yourpassword");
                int count = pop3Client.GetMessageCount();
                messages.Clear();
                int success = 0;
                int fail = 0;
                for (int i = count; i >= 1; i -= 1)
                {
                    try
                    {
                        Application.DoEvents();
                        string body;
                        Message message = pop3Client.GetMessage(i);
                        MessagePart plainTextPart = message.FindFirstPlainTextVersion();
                        if (plainTextPart != null)
                        {
                            // The message had a text/plain version - show that one
                            body = plainTextPart.GetBodyAsText();
                        }
                        else
                        {
                            // Try to find a body to show in some of the other text versions
                            List<MessagePart> textVersions = message.FindAllTextVersions();
                            if (textVersions.Count >= 1)
                                body = textVersions[0].GetBodyAsText();
                            else
                                body = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>";
                        }
                        // Build up the attachment list
                        List<MessagePart> attachments = message.FindAllAttachments();
                        foreach (MessagePart attachment in attachments)
                        { }

                        // Add the message to the dictionary from the messageNumber to the Message
                        messages.Add(i, message);


                        success++;
                    }
                    catch (Exception e)
                    {

                        fail++;
                    }
                }
            }
            catch (InvalidLoginException)
            {
                //MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication");
            }
            catch (PopServerNotFoundException)
            {
                //MessageBox.Show(this, "The server could not be found", "POP3 Retrieval");
            }
            catch (PopServerLockedException)
            {
                //MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked");
            }
            catch (LoginDelayException)
            {
                //MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay");
            }
            catch (Exception e)
            {
                //MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval");
            }
            finally
            {

            }
        }
    }
}

7 Responses to “POP3 client using c#”

  1. pop3 said

    The getmessagecount() method does not give the accurate count of the emails. It gives only 103 whereas there are 600 emails in the inb0x?

    • vivekcek said

      Check your pop forward settings.Re enable it or set down load all from current date.This issue regards ur mail providers pop download settings

    • you should write something like this :
      pop3Client.Authenticate(“recent:username”, “password”);

      and
      to get the latest one email ,

      Pop3Client pop3Client = new Pop3Client();
      pop3Client.Connect(“pop.gmail.com”, 995, true);

      pop3Client.Authenticate(“recent:username”, “password”);

      int count=pop3Client.GetMessageCount();
      Message message = pop3Client.GetMessage(count);

  2. // i love this code to get Only Last Message (simple) write next method
    private string getLastMailMessage()
    {

    try
    {

    if (pop3Client.Connected)
    pop3Client.Disconnect();
    pop3Client.Connect(“pop.gmail.com”, 995, true);
    pop3Client.Authenticate(“mail.matching@gmail.com”, “abc123456?”);
    int count = pop3Client.GetMessageCount();

    try
    {

    Application.DoEvents();

    string body;
    Message message = pop3Client.GetMessage(count);

    MessagePart plainTextPart = message.FindFirstPlainTextVersion();

    body = plainTextPart.GetBodyAsText();
    return body;

    }
    catch (Exception e)
    {
    return e.Message;
    }
    }
    catch (InvalidLoginException)
    {
    return “The server did not accept the user credentials! \n POP3 Server Authentication”;
    }
    catch (PopServerNotFoundException)
    {
    return “The server could not be found \n POP3 Retrieval”;
    }
    catch (PopServerLockedException)
    {
    return “The mailbox is locked. It might be in use or under maintenance. Are you connected else where? \n POP3 Account Locked”;
    }
    catch (LoginDelayException)
    {
    return “Login not allowed. Server enforces delay between logins. Have you connected recently? \n POP3 Account Login Delay”;
    }
    catch (Exception e)
    {
    return “Error occurred retrieving mail. ” + e.Message+ “\n POP3 Retrieval”;
    }

    }

  3. hafiz said

    I m trying to use this code in web application but I got error at ” if (pop3Client.Connected)” this line what is the problem ???

  4. vinay kumar said

    will you post the send Email functionality using Pop3client server in web api c#?

Leave a comment