如何使用C#访问POP3服务器(转)
2024-07-21 02:20:17
供稿:网友
//希望通过这篇文章,你可以用c#写出自己的email客户端程序
this is a follow up to my smtp example that shows how to access your pop3 server. this program connects and logs on to your pop3 server, and checks to see how many new messages you have.
the instantiation of the pop is in main() like this:
pop pop = new pop("pop-server", "loginname", "password"); you must replace "pop-server" with the name of your pop server, "loginname" with your own log in, and "password" with your password. the class has two methods. the connect method takes care of actually logging in to the server. the tcpclient class is used to establish the connection. the "user" and "pass" commands are used to login. connect returns a networkstream object created during the connection process. the second method is getnumberofnewmessages, which returns the number of unread messages on the server. the response to the "stat" command is parsed to extract the number of new messages.
requirement:
requires .net sdk
how to compile?
csc /r:system.net.dll /r:system.io.dll pop.cs
source code
using system.net.sockets;
using system.io;
using system.net;
using system;
class pop
{
string popserver;
string user;
string pwd;
public pop(){}
public pop(string server, string _user, string _pwd)
{
popserver = server;
user = _user;
pwd = _pwd;
}
private networkstream connect()
{
tcpclient sender = new tcpclient(popserver,110);
byte[] outbytes;
string input;
networkstream ns = null;
try{
ns = sender.getstream();
streamreader sr = new streamreader(ns);
console.writeline(sr.readline() );
input = "user " + user + "/r/n";
outbytes = system.text.encoding.ascii.getbytes(input.tochararray());
ns.write(outbytes,0,outbytes.length) ;
console.writeline(sr.readline() );
input = "pass " + pwd + "/r/n";
outbytes = system.text.encoding.ascii.getbytes(input.tochararray());
ns.write(outbytes,0,outbytes.length) ;
console.writeline(sr.readline() );
return ns;
}
catch(invalidoperationexception ioe){
console.writeline("could not connect to mail server");
return ns;
}
}
public int getnumberofnewmessages()
{
byte[] outbytes;
string input;
try{
networkstream ns = connect();
streamreader sr = new streamreader(ns);
input = "stat" + "/r/n";
outbytes = system.text.encoding.ascii.getbytes(input.tochararray());
ns.write(outbytes,0,outbytes.length);
string resp = sr.readline();
console.writeline(resp);
string[] tokens = resp.split(new char[] {' '});
input = "quit" + "/r/n";
outbytes = system.text.encoding.ascii.getbytes(input.tochararray());
ns.write(outbytes,0,outbytes.length);
console.writeline(sr.readline());
sr.close();
ns.close();
return tokens[1].toint32();
}
catch(invalidoperationexception ioe){
console.writeline("could not connect to mail server");
return 0;
}
}
public static void main()
{
pop pop = new pop("pop-server", "loginname", "password");
console.writeline("new messages = {0}", pop.getnumberofnewmessages() );
console.readline();
}
}