Read pop3 email attachments component

kick it on DotNetKicks.com

How simple it is to read your first hotmail email? Check it out here

    You came here to read pop3 email using C#.net.  after reading all below mentioned steps,

You would be able to create your own email component to read POP3 email.

In this article I will explore how to read your pop3 email using C#.

It will help you to parse email attachment, found as BASE64 string and convert it into Binary.



Note* there are very few commands required to communicate with pop3 server.

 e.g.

1. LIST 
2. RETR
3. STAT
4. USER
5. PASS
6. DELE
7. QUIT

 



If you search over the net about RFC POP3 then you will get more details about these commands.

Let us see how to use these pop3 commands.

Here we will open connection with your pop3 server and to this stream we will authonticate your request,
read email, using those pop3 commands.

    We will use System.Net and Socket programming to achieve our goal.

Below is  self explanatory core library  that will send POP3 commands to your pop3 server

 using System;

using System.Collections.Generic;

using System.Text;

using System.Net;

using System.Net.Sockets;

using System.Net.Security;

using System.IO;

using System.Threading;

public class TCPclient

{

private string _popServer;
public string PopServer

{

get{return _popServer;}

set{_popServer = value;}

}

 

private int _popPort;public int PopPort

{

get{return _popPort;}

set{_popPort = value;}

}

private string _loginName;public string LoginName

{

get{return _loginName;}

set{_loginName = value;}

}

private string _password;public string Password

{

get{return _password;}

set{_password = value;}

}

private string _email;private string Email

{

get { return _email; }

set { _email = value; }

}

TcpClient tcpclient = new TcpClient();

NetworkStream ntstrm;

StreamReader strmR;

StreamWriter strmW;

public void Connect()

{

if (!tcpclient.Connected)

{

tcpclient.Connect(_popServer, _popPort);

ntstrm = tcpclient.GetStream();

strmR =
new StreamReader(ntstrm);

strmW = new StreamWriter(ntstrm);strmW.WriteLine(

"USER " + _loginName);

strmW.Flush();

strmW.WriteLine(
"PASS " + _password);

strmW.Flush();

}

}

public string SendCommand(string command)

{

string strTemp = command;

//foreach(string str in parm)

//{

// command+=" " ;

// command+=str;

//}

//strmW.WriteLine("LIST");

//strmW.Flush();

strmW.WriteLine(command);

strmW.Flush();

return GetResponse(command);

}

private string GetResponse(string command)

{

string line = string.Empty;

Thread.Sleep(2000);

if (command == "STAT")

{

line = strmR.ReadLine();

}

else

{

Thread.Sleep(3000);byte[] arrResponse = new byte[10000000];

ntstrm.Read(arrResponse, 0, arrResponse.Length);

string str = System.Text.Encoding.ASCII.GetString(arrResponse);

return str;

}

 

return line;

}

public void CloseConnection()

{

tcpclient.Close();

ntstrm.Close();

strmR.Close();

strmW.Close();

}

}



Now, create you ASPx page  That will accept POP3 server Name , User name , Password, and port number genrally its 110 to read unsecure email.

 TCPclient tcpclient = new TCPclient();
private void button1_Click(object sender, EventArgs e)

{

string response = string.Empty;

 

tcpclient.PopServer = txtPop.Text;

tcpclient.PopPort =
int.Parse(txtPort.Text);

tcpclient.LoginName = txtUserName.Text;

tcpclient.Password = txtPassword.Text;

tcpclient.Connect();

response = tcpclient.SendCommand("LIST");response = tcpclient.SendCommand(

"STAT");

// Regex re = new Regex();

MatchCollection mc = Regex.Matches(response, @"\bOK\s\d+\s\b");foreach (Match m in mc)

{

    txtResponse.Text = tcpclient.SendCommand("RETR " + m.Value.Replace("OK",""));

    if (txtResponse.Text.IndexOf("attachment") != -1)

   {

      // Here we will parse the attachemnt

      code to parse email and find attachments

      StoreAttachments();

    }

 }

}


public void StoreAttachments()
{

List<string> lstFilename = new List<string>();

Regex reFilename = new Regex(@"\bfilename=\""(.*)\b");

MatchCollection mFilename = reFilename.Matches(txtResponse.Text);

foreach (Match mf in mFilename)

{

lstFilename.Add(mf.Groups[1].Value);

}

 

foreach (string strfileName in lstFilename)

{

writeFile(strfileName,
            parseValue(txtResponse.Text,
@"Content-Disposition: attachment; filename="""+ strfileName+ "\"","--",false));

}

}

private void writeFile(string fileName, string fileContent)

{

try

{

FileStream fs = new FileStream(@"c:\" + fileName, FileMode.CreateNew); fs.Write(Convert.FromBase64String(fileContent),0,
               Convert
.FromBase64String(fileContent).Length);

fs.Close();

}

catch (Exception ex)

{

 // see if any exception here

}

}


 



Parse attachment The BASE 64 string  / find BASE 64 string in email

private string parseValue(String responseBody, String prefix, String posix, bool include1)

{

String action;

int i;

//try to find the first type

i = responseBody.IndexOf(prefix);

if (i >= 0)

{

if (include1)

{

action = responseBody.Substring(i);

}

else

{

action = responseBody.Substring(i + prefix.Length);

}

if (!posix.Equals(""))

action = action.Substring(0, action.IndexOf(posix));

return action.Trim();

}

throw new Exception("Value '" + prefix + "' not found");


 


Satalaj 


 

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.