Let’s see how to read emails from a pop3 Server.

After setting some variables, we’ll create a connection to the Pop3 Server and we’ll try to autenticate with user and password. After we’ll take a bunch of messages and we’ll start to iterate some operation per each message.

C Sharp

C#

The message can be cleaned, processed, saved or used in any way you want.
After we’ll delete the message from the server and we’ll disconnect the user.
To do this we’ll use an external library called IndipendentSoft.Email so at the beginning of the file we’ll include these 2 lines:

using Independentsoft.Email.Pop3;
using Independentsoft.Email.Mime;

Now we can write code we need.

public int checkPop3()
{
	WriteLog("- checkPop3 START");
	Pop3Server = rootkey.GetValue("POP3Server").ToString();
	Pop3User = rootkey.GetValue("POP3User").ToString();
	Pop3Pass = "your-password"

	int myResult = 0;
	int myStep = 0;
	int messageIndex = 0;
	int mymaxdelfor = 20; //how many messages to read per each connection
	Pop3Client client = null;

	Independentsoft.Email.Mime.Message myMessage = null;
	String myCode = "";
	myStep = 1;
	client = new Pop3Client(Pop3Server);
	try
	{
		client.Connect();
		WriteLog("Conn POP3: OK");
	}
	catch (Exception myEx)
	{
		WriteLog("Conn POP3: KO" + myEx.ToString());
		return 0;
	}
	try
	{
		client.Login(Pop3User, Pop3Pass);
		WriteLog("Login POP3: OK");
	}
	catch (Exception myEx2)
	{
		WriteLog("Login POP3: KO" + myEx2.ToString());
		return 0;
	}
	MessageInfo[] messageInfo;
	try
	{
		messageInfo = client.List();
		WriteLog("List POP3: OK");
	}
	catch (Exception myEx3)
	{
		WriteLog("List POP3: KO" + myEx3.ToString());
		throw;
	}
	
	myStep = 2;
	if (messageInfo.Length > 0)
	{
		WriteLog("MSG to read: " + messageInfo.Length);
		myStep = 3;
		if (messageInfo.Length < mymaxdelfor)
		{
			mymaxdelfor = messageInfo.Length;
		}

		for (int i = 0; i < mymaxdelfor; i++)
		{
			WriteLog("MSG n." + messageIndex.ToString());
			messageIndex = messageInfo[i].Index;
			myMessage = client.GetMessage(messageIndex);
			myStep = 4;
			
			DoYourThings();
			...
			myResult = "dependsOnYourThings";
			...
			
		}
			client.Delete(messageIndex);
	}
		client.Disconnect();
		WriteLog("DISCONNECT POP3 OK");
	
	WriteLog("- checkPop3 END");
	return myResult;
}

The number of messages to read in a box, can be very high, even hundreds of thousands and not just because of spam but according to the application and email purpose.
So in time I experienced that for high volumes and big size emails it is better not to read all the messages. So I choose a maximum (20) per each connection.

Of course you can read the pop3 according to some events or call your function every some minutes according to a timer.

Enjoy.