29. September 2009 12:54
Days ago I come across the post saying hotmail is offering pop3. So I re-written my previos read gmail pop3 code to see how it works with hotmail.
This article will read your first hotmail email. I have explained the commands that we can use with POP3.
I'm using ASP.net with C#.net and TcpIPClient to read email.
I saw many developers are searching for the code to read an email programatically.
I have created test user to use below code.
UserName: satalajmore@hotmail.com
password: Passw@rd
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;
public partial class pop : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_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("pop3.live.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("pop3.live.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 satalajmore@hotmail.com");
// sent to server
sw.Flush();
sw.WriteLine("PASS Passw@rd");
sw.Flush();
// RETR 1 will retrive your first email.
// It will read content of 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 hotmail email ");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
Note* there are very few commands required to communicate with pop3 server.
You can use below commands to perform the operations on your pop3 server.
For more details about below command please refer RFC http://www.ietf.org/rfc/rfc1939.txt
e.g.
1. LIST
2. RETR
3. STAT
4. USER
5. PASS
6. DELE
7. QUIT
You can use above command instead of RETR
sw.WriteLine("STAT 1");
sw.Flush();
I'm using System.Net.Security.SslStream becaus hotmail accepts secure socket.
-Satalaj