C#的PoP3连接
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- using System.Net.Sockets;
- using System.IO;
- using System.Net;
-
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- POP pop3 = new POP("E-Mail.Server", "UserName", "PassWord");
- Console.WriteLine("New Messages = {0}", pop3.GetNumberOfNewMessages());
- Console.ReadLine();
- }
- }
-
- class POP
- {
- string POPServer;
- string user;
- string pwd;
- public POP() { }
- public POP(string _popserver, string _user, string _pwd)
- {
- POPServer = _popserver;
- 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("1:" + sr.ReadLine());
-
- input = "user " + user + "\r\n";
- outbytes = System.Text.Encoding.ASCII.GetBytes(input.ToCharArray());
- ns.Write(outbytes, 0, outbytes.Length);
- Console.WriteLine("2:" + sr.ReadLine());
-
- input = "pass " + pwd + "\r\n";
- outbytes = System.Text.Encoding.ASCII.GetBytes(input.ToCharArray());
- ns.Write(outbytes, 0, outbytes.Length);
- Console.WriteLine("3:" + 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("4:" + 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("5:" + sr.ReadLine());
-
- sr.Close();
- ns.Close();
-
- return Convert.ToInt32(tokens[1]);
- }
- catch (InvalidOperationException ioe)
- {
- Console.WriteLine("Could not connect to mail server");
- return 0;
- }
- }
- }
-
- }