Satalaj More

Excellent web architect.[Working hard to make things very very simple)]

ASP.net Read Email

Hi,
 This is Satalaj, here is simple way of reading your gmail email using ASP.net web application
Before using this code make sure you are able to access your gmail email using outlook
if not then login to www.gmail.com click on settings => pop => check to access email outside gmail web client

You can read your hotmail, if you are facing problem with gmail try below link

http://www.revenmerchantservices.com/post/2009/09/29/ASPnet-read-email-hotmail.aspx 

If you are not using gmail Secure socket layer.

try http://www.revenmerchantservices.com/page/Read-pop3-email-attachments-component.aspx

Above post will work with your company email POP3.


 Refer POP rfc  http://www.faqs.org/rfcs/rfc1939


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

{

// 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 flag

// Asssigned the writer to stream 

System.IO.StreamWriter sw = new StreamWriter(sslstream);

// Assigned reader to stream

System.IO.StreamReader reader = new StreamReader(sslstream);

// refer POP rfc command, there very few around 6-9 command

sw.WriteLine("USER your_gmail_user_name@gmail.com");

// sent to server

sw.Flush();

sw.WriteLine("PASS your_gmail_password");

sw.Flush();

// this will retrive your first email

sw.WriteLine("RETR 1");

sw.Flush();

// close the connection

sw.WriteLine("Quit ");

sw.Flush();

string str = string.Empty;

string strTemp = string.Empty;

while ((strTemp = reader.ReadLine()) != null)

{

// find the . character in line

if (strTemp == ".")

{

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);

}

}



 

Comments

Seila said:

At home I will test your code...

but I just wanna congrat u to share =)

Cheers

Seila

# July 1, 2008 1:50 PM

ajaybanzal said:

Great, I congrtulate you on this excellent code.

Ajay Banzal

# July 9, 2008 8:56 AM

satalaj said:

Hi are you able to access your gmail emails via Microsoft Outlook or Outlook Express?

If not then you need to login to your gmail

Then click on  settings select POP service and make sure it is checked to allow POP access to other clients

Satalaj

# September 29, 2008 10:47 AM

umesh said:

I tried your code with my comapny's mail id but i got error "The handshake failed due to an unexpected packet format."

at line

sslstream.AuthenticateAsClient("pop.gmail.com");

I give here my pop server's Id.

Also i tried it with gmail also but i am unable to read mail from gmail also.

Please guide me to read mail body and attachment from my inbox.

# October 16, 2008 5:17 AM

satalaj said:

Hi Umesh,

To work with your company email Id. First you should know your pop server and its port number. then replace

the appropriate pop.gmail.com with yours and use your credentials provided by your company id.

To read attachments you need to write down your parser which will search BASE64 sting in a file then convert that Base64 String into bytes and save it using appropriate extension. Please refer RFC pop.

# October 16, 2008 9:09 AM

raj said:

hiiii

i tried your code...but i can not access my mail from gmail. In gmail setting i allowed pop.

plz tell me solution.

# October 21, 2008 9:05 AM

satalaj said:

Hi Raj,

 Are you able to access gmail using outlook? If yes then you should be able to access it using the code.

Make sure there is no firewall blocking the port at your end.

Execute the code step by step.

# October 21, 2008 9:28 AM

almny_com said:

thanks

i searching about it :)

# October 28, 2008 6:12 AM

Babuni said:

Hi Satlaja,

              I tried your code.i am getting the below output but i want to retrieve the content of the mail.

+OK Gpop ready for requests from 121.243.162.89 30pf974964hso.0

Congratulation.. ....!!! You read your first gmail email

# November 6, 2008 11:58 PM

satalaj said:

Hi Babuni,

You need to debug the code. While debugging wait for

3 sec. and then go ahead next line. I see you are very close to get it done

Satalaj-

# November 7, 2008 2:35 AM

mamun said:

Hello,

 How to display the unread message count.That is Iwant to say after sign in,"You have 3 new mail".How to do it.

 Moreover,I want to show only the subject and the sender.How to do it?

 And,This code don't run if I use a proxy server.Is it possible to run it using proxy server and if possible then how?

Thanks

Mamun

# November 8, 2008 6:24 AM

satalaj said:

Hi mamun,

The email service provider should support IMAP protocol instead of POP. Gmail supports IMAP however they don;t allow third party client to get notification of unseen email count :(

I'm not sure but it can be done in Proxy Environment also. Let me know your workaround.

Satalaj

# November 8, 2008 7:04 PM

Mamun said:

Thanks Satalaj for you quick reply.

I am using Windows Server2003 and using proxy server.My proxy server ip is 172.16.1.49 and port is 8080.I saw this information in my internet explorer.

The code which you provide is run when I connect without proxy server and I can easily read my gmail.But,I need to work it using proxy server.I aslo need to notify the user about his new or unread email,When he sign in using his gmail or yahoo mail.I also need the list of unread mail's subject name and the sender name and a link to view that email.

It is urgent.Please help me.Please expalin details and of course with source code.

Thanks.

Mamun

# November 8, 2008 11:41 PM

satalaj said:

Hi Mamun,

Though gmail is supporting IMAP they don;t allow  such unseen / unread notification for third party email client like you are going to build.

You can do it this way

bobpeers.com/.../telnet_imap.php

you need to convertthe Telnet code into C#, I mean you need to execute telnet command using C# code and TCPClient.

# November 10, 2008 1:06 AM

Dillon Riecke said:

Thanks so much for this! I will attempt to modify it to read company emails from a non-google server. This is a heavensent.

# November 17, 2008 1:25 PM

Kelvin Kong said:

Thanks Satalaj Share the excellent code.

I can read the emails.But it's error if it have attachment.

Error on end :

Received an unexpected EOF or 0 bytes from the transport stream

Could you give me a way to solve it ,Thanks a lot!

# November 26, 2008 7:30 AM

Albert said:

Hi  Satalaj,

I also get similar response like;

+OK Gpop ready for requests from 121.243.162.89 30pf974964hso.0

Congratulation.. ....!!! You read your first gmail email

But i cannot see the contents of the message.

# December 1, 2008 5:47 AM

Albert said:

Hi Satalaj,

It works, although i cannot see the message subject and body.

# December 2, 2008 5:08 AM

xyz said:

if you don't know anything than try to be act smart it shows your stupidity.

# January 16, 2009 5:56 AM

Shreekala said:

Hi satalaj,

The code works fine ,but how can I retrive unread un deliverable mails.

I want to retrive To  emailids How can I do this.

I used following codes to connect to the company mail server

Pls help me.

tcpclient.Connect(mail_server, 110);

                StreamReader RdStrm;

                string Data;

                byte[] szData;

                string CRLF = "\r\n";

                NetworkStream stream = tcpclient.GetStream();

                Data = "USER " + "UserName" + CRLF;

                szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());

                stream.Write(szData, 0, szData.Length);

                Data = "PASS " + "Password" + CRLF;

                szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());

                stream.Write(szData, 0, szData.Length);

                Data = "STAT" + CRLF;

                szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());

                stream.Write(szData, 0, szData.Length);

                Data = "RETR " + "4" + CRLF;

                szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());

              stream.Write(szData, 0, szData.Length);

               // Data = "LIST " + CRLF;

                //szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());

               // stream.Write(szData, 0, szData.Length);

                RdStrm = new StreamReader(stream);

               string  szTemp = RdStrm.ReadLine();

                string str="";

                if (szTemp[0] != '-')

                {

                    while (szTemp != ".")

                    {

                       str += szTemp;

                       szTemp = RdStrm.ReadLine();

                    }

                }

# January 19, 2009 4:57 AM

shreekala said:

Hi,

How to get unread mail count using pop3

# January 21, 2009 12:17 AM

IamMadan said:

Hi mamun,

I am getting an exception while connecting to the server

in the line:

System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream());

Exception I got is:

"The operation is not allowed on non-connected sockets."

can you help me to solve this....

# March 25, 2009 9:11 AM

Rokan said:

Hi,

When i m retriving mail i got the following error

Unable to read data from the transport connection: An established connection was aborted by the software in your host machine

Sometimes i got the following message

+OK Gpop ready for requests from 114.134.90.222 25pf2174468tif.14 Congratulation.. ....!!! You read your first gmail email

but i can't read the mail

i can access my gmail from outlook.

# April 1, 2009 1:37 AM

manjul dayal said:

 I tried your code.i am getting the below output but i want to retrieve the content of the mail.

+OK Gpop ready for requests from 121.243.162.89 30pf974964hso.0

Congratulation.. ....!!! You read your first gmail email

should I decode the line of code

# April 4, 2009 7:38 AM

gautam said:

im getting the error

as below :

"Unable to read data from the transport connection: An established connection was aborted by the software in your host machine."

at below line during flush

           sw.WriteLine("RETR 1") '' this will retrive your first email

           sw.Flush()

Please help

# April 16, 2009 11:48 AM

Balaji R said:

Hi hw to read content of the gmail.Cn u hlp me?

# May 6, 2009 2:29 AM

satalaj said:

Hi Balaji.

To read the content of email you need to write your own parser which will parse what you have received using that code.

# May 26, 2009 11:02 AM

Madhu said:

Hi satalaj ,

Thanks Fro your code, I need to red the attchments also. How i do with this code? Please Let me know

# July 9, 2009 7:26 AM

satalaj said:

Madhu,

To read attachment you need to parse the email content. Parse the content to find BASE64 character string Then conver the BASE64 in to Bytes and Save the Bytes in to original file.

I will be posting that code soon on my site

www.revenmerchantservices.com

# July 9, 2009 7:45 AM

Rangapure.S.Swapnil said:

i got the output as

+OK Gpop ready for requests from 202.177.151.122 l28pf2050723waf.27

Congratulation.. ....!!! You read your first gmail email

now how to read the inbox mail.?

u told in post as"To read the content of email you need to write your own parser which will parse what you have received using that code. "

how to write the parser..

can u pls provide detail code..of parser

# July 16, 2009 6:22 AM

satalaj said:

swapnil,

you need to read an email using POP RPC command

like retr list

# July 16, 2009 9:08 AM

aarthimaneksha said:

hi

excellent code

it works!

thanks for the code

# July 27, 2009 4:32 AM

satalaj said:

# July 27, 2009 6:01 AM

satalaj said:

I have No Idea about it. I think it is required to wait for connection.

# July 29, 2009 6:57 AM

Meetu Choudhary said:

Geetting Erroe :

-ERR bad command l37pf1694331waf.20

Your code is not reading the mail.

# August 19, 2009 1:07 AM

M said:

Error:

The handshake failed due to an unexpected packet format.

# August 19, 2009 7:01 AM

satalaj said:

Hi Lauren,

You need to create email parser which will

extract subject and body of an email.

Thanks, Satalaj.

# October 23, 2009 4:22 AM

satalaj said:

You can try Parsing of email body, subject, from email, to email etc.. like this

www.codeproject.com/.../SimplePop3Class.aspx

# October 30, 2009 2:56 AM

Lauren said:

Hi,

I've managed to get the code to only extract the body if the email.

I just wanted to know - is there a way to get only unread emails from the inbox? I've tried using the "RETR LIST" command, but I'm not sure whether I am going the right way.

Regards,

Lauren

# November 2, 2009 3:35 AM

satalaj said:

Hi Lauren,

To read unseen messages you need to use IMAP protocol instead of POP. Gmail supports IMAP but it

has blocked the unseen messages to read via thirdparty clients. You need to talk with your email service provider to get an access to IMAP.

Here are those RPC IMAP commands that you can use in your

application marco.uminho.pt/.../comandosPOP_IMAP.pdf

Thanks, Satalaj.

# November 3, 2009 12:04 AM

satalaj said:

Hi shri,

The intention of providing such code is to let the beginners learn how socket programming works or how to read basic email using C# asp.net TcpIPclient.

-Satalaj.

# November 6, 2009 7:02 AM

satish verma said:

Hi..

i want to access inbox mail and spam mail

Please guide me.....

# November 23, 2009 5:03 AM

preeja.preeja said:

Hellow satalaj,

i tried this code but getting the below output

+OK Gpop ready for requests from 202.164.................

Congratulation.. ....!!! You read your first gmail email

how can i read the mail!

# December 1, 2009 5:11 AM

satalaj said:

hi preeja.preeja,

Please try the same code using hotmail account.

www.revenmerchantservices.com/.../ASPnet-read-email-hotmail.aspx

satalaj

# December 1, 2009 5:21 AM

satalaj said:

Hi satish verma,

You need to use IMAP not POP3

to read inbox and other user created folders.

Satalaj

# December 1, 2009 5:22 AM

manuc said:

i tried ur code , but its not wsorking and givig error like this " Unable to read data from the transport connection: An established connection was aborted by the software in your host machine. "

Pls give me a solution for this,

Thanking you

# March 3, 2010 12:03 AM

satalaj said:

@manuc, May be your internal firewall system or anti virus is blocking the connection on that port.

or you are accessing connection via proxy server

Satalaj

# March 3, 2010 12:10 AM

manuc said:

Sorry i am not using proxy server, any other chance to get this error.

# March 3, 2010 1:02 AM

satalaj said:

@Manuc,

Are you able to open a command promt and execute

Telnet pop.gmail.com 995

If connected it will give you blank screen.

Satalaj

# March 3, 2010 1:39 AM

manuc said:

Yeah its connecting.

# March 3, 2010 1:49 AM

satalaj said:

@Manuc,

Do you have antivirus installed? Can you disable it

and then try

Satalaj

# March 3, 2010 2:32 AM

manuc said:

yeah i have disable the antivirus and run, but now also it showing the error like this " A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond "

So please find any solution for this,

Thanking you

# March 3, 2010 6:17 AM

Alessandro said:

I have the same error: " Unable to read data from the transport connection: An established connection was aborted by the software in your host machine. "

This happen only when i try to read the body of an e-mail of witch i now the ID because i can read and saver the list of all ID of e-mail in the mailbox.

Is there a solution for this?

Thanx!

# April 29, 2010 9:17 AM

Rahul Barpha said:

Error :

Unable to write data to the transport connection: An established connection was aborted by the software in your host machine

# September 28, 2010 8:30 AM

Pranjal said:

Hi,

Thanks for code but after click on button, after taking a long time, it can not give an error nor reading mails.

Is there any solution.

# November 28, 2010 8:00 AM

joth said:

i made one appllication ,through which we can access our gmail inbox.but only 297 messages are showing in inbox...i have more than 1000 msgs in my mailbox...ie, latest 700 msgs are not showing....how will rectyfy this problem...plz help me....

# July 27, 2011 6:33 AM

hazarath said:

it is reading single mail

how is for n number of mails

# August 18, 2011 5:45 AM

dripable service said:

Markedly well written read!!

# November 10, 2011 9:33 PM

Dripable.com said:

This makes perfect sense!

# November 10, 2011 10:06 PM

d devloper said:

HI satalaj,

Thanks for your code.

It is working fine for gmail .But I want to use it for our company mail.Although I have changed all those setting but it is not retrieving the mail from server.

Any help???

Is it possible to read all the unread messages??

Please rply???

thanks and Regards

dj

# November 17, 2011 7:02 AM

john said:

May I ask you the whole code of this project? .. cause i can't run it in my app ...

thank you

# December 3, 2011 2:52 AM

anatolium said:

hello

I have read all the comments.I do not understand anything.

+OK Gpop ready for requests from 188.119.9.143 t9pf70806550eeb.20

Congratulation.. ....!!! You read your first gmail email

I can not see my email !!!

thank you

# December 29, 2011 2:42 PM