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

}

}


you can Comment or discuss here http://www.revenmerchantservices.com/post/2009/06/01/ASpnet-Read-gmail-email.aspx

 

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

serdar said:

I test it your code

After connection last line server send

530-5.5.1 Authentication Required. Learn more at                    

530 5.5.1 mail.google.com/.../answer.py j34sm463303ugc.47

gmail account end pwd is correct

# September 29, 2008 10:24 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

Mamun said:

Hello satalaj,

 Thanks for your reply.At last I can do that.But I don't use any socket.I use the google's atm xml file for all kinds of new email acces,email count,read etc.

I found this kinds of help from the following link:

www.codeproject.com/.../GMailReader.aspx

This is written in C# and I converted as my need using ASP.NET.

 Again thanks and greatefull to you by promoting to me using your idea.

Thanks

Mamun

# November 11, 2008 1:25 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

khurram said:

Sir I try your code and get this message

+OK Gpop ready for requests from 94.99.127.29 j6pf6949245mue.11

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

I like to store all me email in SQL data table please heal me to read email from gmail

thanks

khurram (techmind786@gmail.com)

# December 29, 2008 5:38 AM

mona.sandeep said:

Hii... am getting the following error..

+OK Gpop ready for requests from 59.90.214.12

20pf56833018wfi.50

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

i followed the debugging procedure but it didnt worked.. pls help me..

thank u..

# January 8, 2009 3:12 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

sanket said:

hello  sir,

i m trying this code but i got this o/p

+OK Gpop ready for requests from 202.177.151.122 l28pf2050723waf.27

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

how can i read  the mail please send me code or details on my id- thombre.sanket@yahoo.co.in

# July 20, 2009 6:35 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

ウェブ開発者 said:

nice!

sometimes in code debugging, instead of waiting,

how about making a while, then a part that indicates the message.

I also encountered such scenario when making a system that access cisco equipment thru telnet, then it is either wait for few seconds before close or scan for some text, capture it then close

# July 29, 2009 6:20 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

Lauren said:

Hi,

I have got the code working, however, I only want the body of the message, not all the header information as well. Is there a way to only display the message body, and only if certain text appears in the subject of the email?

Any suggestions would be most appreciated.

Thanks,

Lauren

# October 23, 2009 3:59 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

shri said:

Useless code gives no subject,from,to,body and other details ..not well formed code...

below link is worth download

www.codeproject.com/.../despop3client.aspx

# November 6, 2009 6:42 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
Leave a Comment

(required) 

(required) 

(optional)

(required)