C# .NET - How to read mail from POP3 inbox using c#

Asked By santhosh kumar on 14-Jun-13 08:29 AM
How to programmatically read email from the POP3 mail inbox using .NET

See this code to read mail from POP3

Sagar P replied to santhosh kumar on 17-Sep-08 03:51 AM
Steps
1. create new asp.net web application
2. add one button in it
3. on button click write following code

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net.NetworkInformation;
using System.Net.Security;
using System.Net.Sockets;
protected void Button9_Click(object sender, EventArgs e) 
{
try
{
TcpClient tcpclient = new TcpClient(); // create an instance of TcpClient
tcpclient.Connect("pop.gmail.com", 995); // HOST NAME POP SERVER and gmail uses port number 995 for POP 
System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream()); // This is Secure Stream // opened the connection between client and POP Server
sslstream.AuthenticateAsClient("pop.gmail.com"); // authenticate as client 
//bool flag = sslstream.IsAuthenticated; // check flag 
System.IO.StreamWriter sw = new StreamWriter(sslstream); // Asssigned the writer to stream
System.IO.StreamReader reader = new StreamReader(sslstream); // Assigned reader to stream
sw.WriteLine("USER your_gmail_user_name@gmail.com"); // refer POP rfc command, there very few around 6-9 command
sw.Flush(); // sent to server
sw.WriteLine("PASS your_gmail_password"); 
sw.Flush();
sw.WriteLine("RETR 1"); // this will retrive your first email 
sw.Flush();
sw.WriteLine("Quit "); // close the connection
sw.Flush();
string str = string.Empty; 
string strTemp = string.Empty;
while ((strTemp = reader.ReadLine()) != null) 
{
if (strTemp == ".") // find the . character in line
{
break; 
}
if (strTemp.IndexOf("-ERR") != -1) 
{
break; 
}
str += strTemp;
}
Response.Write(str);
Response.Write("<BR>" + "Congratulation.. ....!!! You read your first gmail email "); 
}
catch (Exception ex) 
{
Response.Write(ex.Message);
}
}

reply

Binny ch replied to santhosh kumar on 17-Sep-08 03:52 AM
try this:
 Outlook.Attachments ii = mail.Attachments;
                                if (ii.Count > 0)
                                {
                                    for (int j = 1; j <= ii.Count; j++)
                                    {
                                        Outlook.Attachment aa = (Outlook.Attachment)ii[j];

                                        //Remove The Row and Then Add The Time;

                                        string mypath = @"D:\ResumeSettings\OutlookMails\" + aa.FileName;
                                        mypath = @mypath;
                                        FileInfo file = new FileInfo(mypath);
                                        string extension = file.Extension;

POP 3

Kalit Sikka replied to santhosh kumar on 17-Sep-08 03:55 AM
 public TcpClient Server;
 public NetworkStream NetStrm;
 public StreamReader  RdStrm;
 public string Data;
 public byte[] szData;
 public string CRLF = "\r\n";

Here's the code for when the Connect Button is clicked:

Collapse
private void ConnectBtn_Click(object sender, System.EventArgs e)
{
    // change cursor into wait cursor
    Cursor cr = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;
    // create server POP3 with port 110
    Server = new TcpClient(POPServ.Text,110);
    Status.Items.Clear();
    try
    {
        // initialization
        NetStrm = Server.GetStream();
        RdStrm= new StreamReader(Server.GetStream());
        Status.Items.Add(RdStrm.ReadLine());
        // Login Process
        Data = "USER "+ User.Text+CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        Status.Items.Add(RdStrm.ReadLine());
        Data = "PASS "+ Passw.Text+CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        Status.Items.Add(RdStrm.ReadLine());
        // Send STAT command to get information ie: number of mail and size
        Data = "STAT"+CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        Status.Items.Add(RdStrm.ReadLine());
        // change enabled - disabled button
        ConnectBtn.Enabled = false;
        DisconnectBtn.Enabled = true;
        RetrieveBtn.Enabled = true;
        // back to normal cursor
        Cursor.Current = cr;
    }
    catch(InvalidOperationException err)
    {
        Status.Items.Add("Error: "+err.ToString());
    }
}    

Here's the code for when the Disconnect Button is clicked:

private void DisconnectBtn_Click(object sender, System.EventArgs e)
{
    // change cursor into wait cursor
    Cursor cr = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;
    // Send QUIT command to close session from POP server
    Data = "QUIT"+CRLF;
    szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
    NetStrm.Write(szData,0,szData.Length);
    Status.Items.Add(RdStrm.ReadLine());
    //close connection
    NetStrm.Close();
    RdStrm.Close();
    // change enabled - disabled button
    ConnectBtn.Enabled = true;
    DisconnectBtn.Enabled = false;
    RetrieveBtn.Enabled = false;
    // back to normal cursor
    Cursor.Current = cr;
}

Here's code when Retrieve Button clicked:

Collapse
private void RetrieveBtn_Click(object sender, System.EventArgs e)
{
    // change cursor into wait cursor
    Cursor cr = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;
    string szTemp;
    Message.Clear();
    try
    {
        // retrieve mail with number mail parameter
        Data = "RETR "+ Number.Text+CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        szTemp = RdStrm.ReadLine();
        if(szTemp[0]!='-') 
        {
            while(szTemp!=".")
            {
                Message.Text += szTemp;
                szTemp = RdStrm.ReadLine();
            }
        }
        else
        {
            Status.Items.Add(szTemp);
        }
        // back to normal cursor
        Cursor.Current = cr;
    }
    catch(InvalidOperationException err)
    {
        Status.Items.Add("Error: "+err.ToString());
    }
}
Hi Sujith - See this code to read mail from POP3
santhosh kumar replied to Sagar P on 17-Sep-08 03:55 AM
I tried this code which was already there in the egghead forum but it is not supporting.. Any other ideas
read mail from POP3 inbox
mv ark replied to santhosh kumar on 17-Sep-08 04:44 AM
Check these links
http://aspalliance.com/240_POP3_Email.all
http://www.codeproject.com/KB/IP/Pop3MailClient.aspx
this will help:
Binny ch replied to santhosh kumar on 17-Sep-08 04:52 AM
//Create Outlook application
Outlook.Application oApp = new Outlook.Application();

//Get MAPI namespace
Outlook.NameSpace oNS = oApp.GetNamespace("mapi");

oNS.Logon("user", "password", false, true);

//Get Messages collection of Inbox
Outlook.MAPIFolder oInbox =
oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFo lderInbox);

Outlook.Items oItems = oInbox.Items;
oNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox );

Outlook.Items oItems;

oItems = objFolder.Items;

//' Read through all the items

for (int i=0; i<objFolder.Items.Count;i++)

{


objMail = (Outlook.MailItem)objFolder.Items.GetNext();

System.Diagnostics.Debug.WriteLine(objMail.Body.ToString());

}
solution
Perry replied to santhosh kumar on 17-Sep-08 09:30 AM

Hi,

I used following code to retrieve mail from POP3 server. You will need two function connect to server and retrieve the mails. You will need to have the permission to read the server contents.

private void ConnectBtn_Click(object sender, System.EventArgs e)
{
    // change cursor into wait cursor
    Cursor cr = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;

    // create server POP3 with port 110
    Server = new TcpClient(POPServ.Text,110);
    Status.Items.Clear();

    try
    {
        // initialization
        NetStrm = Server.GetStream();
        RdStrm= new StreamReader(Server.GetStream());
        Status.Items.Add(RdStrm.ReadLine());

        // Login Process
        Data = "USER "+ User.Text+CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        Status.Items.Add(RdStrm.ReadLine());

        Data = "PASS "+ Passw.Text+CRLF; szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray()); NetStrm.Write(szData,0,szData.Length);
        Status.Items.Add(RdStrm.ReadLine());

        // Send STAT command to get information ie: number of mail and size
        Data = "STAT"+CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        Status.Items.Add(RdStrm.ReadLine());

        // change enabled - disabled button
        ConnectBtn.Enabled = false;
        DisconnectBtn.Enabled = true;
        RetrieveBtn.Enabled = true;

        // back to normal cursor
        Cursor.Current = cr;

    }
    catch(InvalidOperationException err)
    {
        Status.Items.Add("Error: "+err.ToString());
    }
}   

private void RetrieveBtn_Click(object sender, System.EventArgs e)
{
    // change cursor into wait cursor
    Cursor cr = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;
    string szTemp;
    Message.Clear();
    try
    {
        // retrieve mail with number mail parameter
        Data = "RETR "+ Number.Text+CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        szTemp = RdStrm.ReadLine();
        if(szTemp[0]!='-') 
        {
            while(szTemp!=".")
            {
                Message.Text += szTemp;
                szTemp = RdStrm.ReadLine();
            }
        }
        else
        {
            Status.Items.Add(szTemp);
        }
        // back to normal cursor
        Cursor.Current = cr;
    }
    catch(InvalidOperationException err)
    {
        Status.Items.Add("Error: "+err.ToString());
    }
}
http://www.codeproject.com/KB/IP/popapp.aspx
-PAresh
what is the namespace that you should use for objects like cursor and status
santhosh kumar replied to Perry on 17-Sep-08 09:38 AM
Thanks for your reply.what is the namespace that you should use for objects like cursor and status?
name spaces
Perry replied to santhosh kumar on 17-Sep-08 11:44 AM

use below namespaces for this program.

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.Net;

using System.Net.Sockets;

using System.IO;

-Paresh

Secure pop3
Sat Sat replied to Sagar P on 04-Jun-09 05:25 AM
That code only works with secure POP3 not with POP3
Alfred replied to santhosh kumar on 15-Jun-11 11:50 AM
THANKS!! Just what I have been looking for for the past 2 days.
soujanya reddy replied to Perry on 28-Apr-12 02:20 AM
i used this code but am getting an error like this  :    Type or namespace definition, or end-of-file expected   
prasad bhagat replied to mv ark on 16-Oct-12 08:05 AM
re: read mail from POP3 inbox
in step by step process please
help
System.Net.Sockets; protected void Button9_Click(object sender, EventArgs e) { try { / / create an instance of TcpClient TcpClient tcpclient = new TcpClient (); / / HOST NAME POP SERVER and gmail uses port number 995 for POP tcpclient.Connect( "pop.gmail.com" , 995); / / This is Secure Stream / / opened the connection between client and POP Server System.Net.Security. SslStream sslstream = new SslStream (tcpclient.GetStream()); / / authenticate as client sslstream.AuthenticateAsClient( "pop.gmail.com" ); / / bool flag = sslstream.IsAuthenticated; / / check
System.Net.Sockets; protected void Button9_Click( object sender, EventArgs e) { try { / / create an instance of TcpClient TcpClient tcpclient = new TcpClient (); / / HOST NAME POP SERVER and gmail uses port number 995 for POP tcpclient.Connect( "pop.gmail.com" , 995); / / This is Secure Stream / / opened the connection between client and POP Server System.Net.Security. SslStream sslstream = new SslStream (tcpclient.GetStream()); / / authenticate as client sslstream.AuthenticateAsClient( "pop.gmail.com" ); / / bool flag = sslstream.IsAuthenticated; / / check
protected void Page_Load( object sender, EventArgs e) { } protected void Button1_Click( object sender, EventArgs e) { try { TcpClient tcpclient = new TcpClient (); / / create an instance of TcpClient tcpclient.Connect( "pop.gmail.com" , 995); / / HOST NAME POP SERVER and gmail uses port number 995 for POP System.Net.Security. SslStream sslstream = new SslStream (tcpclient.GetStream()); / / This is Secure Stream / / opened the connection between client and POP Server sslstream
System.Net.Security; using System.Net.Sockets; protected void Button9_Click( object sender, EventArgs e) { try { TcpClient tcpclient = new TcpClient(); / / create an instance of TcpClient tcpclient.Connect( "pop.gmail.com" , 995); / / HOST NAME POP SERVER and gmail uses port number 995 for POP System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream()); / / This is Secure Stream / / opened the connection between client and POP Server sslstream
protected void Page_Load( object sender, EventArgs e) { } protected void Button9_Click( object sender, EventArgs e) { try { TcpClient tcpclient = new TcpClient (); tcpclient.Connect( "pop.gmail.com" , 995); System.Net.Security. SslStream sslstream = new SslStream (tcpclient.GetStream()); sslstream.AuthenticateAsClient( "pop.gmail.com" ); System.IO. StreamWriter sw = new StreamWriter (sslstream); System.IO
System.Net.Security; using System.Net.Sockets; protected void Button9_Click( object sender, EventArgs e) { try { TcpClient tcpclient = new TcpClient(); / / create an instance of TcpClient tcpclient.Connect( "pop.gmail.com" , 995); / / HOST NAME POP SERVER and gmail uses port number 995 for POP System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream()); / / This is Secure Stream / / opened the connection between client and POP Server sslstream
System.Net.Security; using System.Net.Sockets; protected void Button9_Click( object sender, EventArgs e) { try { TcpClient tcpclient = new TcpClient(); / / create an instance of TcpClient tcpclient.Connect( "pop.gmail.com" , 995); / / HOST NAME POP SERVER and gmail uses port number 995 for POP System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream()); / / This is Secure Stream / / opened the connection between client and POP Server sslstream
System.Net.Security; using System.Net.Sockets; protected void Button9_Click( object sender, EventArgs e) { try { TcpClient tcpclient = new TcpClient(); / / create an instance of TcpClient tcpclient.Connect( "pop.gmail.com" , 995); / / HOST NAME POP SERVER and gmail uses port number 995 for POP System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream()); / / This is Secure Stream / / opened the connection between client and POP Server sslstream
System.Net.Security; using System.Net.Sockets; protected void Button9_Click( object sender, EventArgs e) { try { TcpClient tcpclient = new TcpClient(); / / create an instance of TcpClient tcpclient.Connect( "pop.gmail.com" , 995); / / HOST NAME POP SERVER and gmail uses port number 995 for POP System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream()); / / This is Secure Stream / / opened the connection between client and POP Server sslstream