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

}

}



 

61 Comments

  • At home I will test your code...

    but I just wanna congrat u to share =)

    Cheers
    Seila

  • Great, I congrtulate you on this excellent code.

    Ajay Banzal

  • 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

  • I tried your code with my comapny&#39;s mail id but i got error &quot;The handshake failed due to an unexpected packet format.&quot;

    at line

    sslstream.AuthenticateAsClient(&quot;pop.gmail.com&quot;);

    I give here my pop server&#39;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.

  • 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.


  • hiiii
    i tried your code...but i can not access my mail from gmail. In gmail setting i allowed pop.
    plz tell me solution.

  • 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.

  • thanks
    i searching about it :)

  • 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

  • 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-

  • 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

  • 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

  • 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

  • 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
    http://bobpeers.com/technical/telnet_imap.php

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

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

  • 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!

  • 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.

  • Hi Satalaj,

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


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

  • 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();
    }
    }

  • Hi,

    How to get unread mail count using pop3

  • 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....

  • 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.

  • 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


  • 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

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

  • 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.

  • Hi satalaj ,

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

  • 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

  • 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

  • swapnil,
    you need to read an email using POP RPC command
    like retr list

  • hi

    excellent code
    it works!
    thanks for the code

  • Read Attcachment using C#

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

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

  • Geetting Erroe :

    -ERR bad command l37pf1694331waf.20

    Your code is not reading the mail.

  • Error:

    The handshake failed due to an unexpected packet format.

  • Hi Lauren,
    You need to create email parser which will
    extract subject and body of an email.

    Thanks, Satalaj.

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

    http://www.codeproject.com/KB/IP/SimplePop3Class.aspx?fid=396225&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2343105

  • 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

  • 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 http://marco.uminho.pt/~osg/CC-I-LESI/ficha2/comandosPOP_IMAP.pdf


    Thanks, Satalaj.

  • 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.

  • Hi..
    i want to access inbox mail and spam mail
    Please guide me.....

  • hi preeja.preeja,
    Please try the same code using hotmail account.
    http://www.revenmerchantservices.com/post/2009/09/29/ASPnet-read-email-hotmail.aspx

    satalaj

  • Hi satish verma,
    You need to use IMAP not POP3
    to read inbox and other user created folders.

    Satalaj

  • 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

  • @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

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

  • @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

  • Yeah its connecting.

  • @Manuc,
    Do you have antivirus installed? Can you disable it
    and then try

    Satalaj

  • 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

  • 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!


  • Error :

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

  • 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.

  • 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....

  • it is reading single mail
    how is for n number of mails

  • Markedly well written read!!

  • This makes perfect sense!

  • 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

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

  • 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

Comments have been disabled for this content.