方法一
using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.Net.Sockets;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Net.Configuration;
using System.Configuration;
#region 邮件接收类
/// <summary>
/// 邮件接收类
/// </summary>
public class POP3
{
#region Fields
string POPServer;
string mPOPUserName;
string mPOPPass;
int mPOPPort;
NetworkStream ns;
StreamReader sr;
#endregion
#region Constructors
/// <summary>
/// POP3
/// </summary>
/// <param name="server">POP3服务器名称 </param>
/// <param name="userName">用户名 </param>
/// <param name="password">用户密码 </param>
public POP3(string server, string userName, string password)
: this(server, 110, userName, password)
{
}
/// <summary>
/// POP3
/// </summary>
/// <param name="server">POP3服务器名称 </param>
/// <param name="port">端口号 </param>
/// <param name="userName">用户名 </param>
/// <param name="password">用户密码 </param>
public POP3(string server, int port, string userName, string password)
{
POPServer = server;
mPOPUserName = userName;
mPOPPass = password;
mPOPPort = port;
}
#endregion
#region Methods
#region Public
/// <summary>
/// 获得新邮件数量
/// </summary>
/// <returns>新邮件数量 </returns>
public int GetNumberOfNewMessages()
{
byte[] outbytes;
string input;
try
{
Connect();
input = "stat" + "\r\n";
outbytes = System.Text.Encoding.ASCII.GetBytes(input.ToCharArray());
ns.Write(outbytes, 0, outbytes.Length);
string resp = sr.ReadLine();
string[] tokens = resp.Split(new Char[] { ' ' });
Disconnect();
return Convert.ToInt32(tokens[1]);
}
catch
{
return -1;
}
}
/// <summary>
/// 获取新邮件内容
/// </summary>
/// <param name="subj">邮件主题 </param>
/// <returns>新邮件内容 </returns>
public List <MailMessage> GetNewMessages(string subj)
{
int newcount;
List <MailMessage> newmsgs = new List <MailMessage>();
try
{
newcount = GetNumberOfNewMessages();
Connect();
for (int n = 1; n < newcount + 1; n++)
{
List <string> msglines = GetRawMessage(n);
string msgsubj = GetMessageSubject(msglines);
if (msgsubj.CompareTo(subj) == 0)
{
MailMessage msg = new MailMessage();
msg.Subject = msgsubj;
msg.From = new MailAddress(GetMessageFrom(msglines));
msg.Body = GetMessageBody(msglines);
newmsgs.Add(msg);
DeleteMessage(n);
}
}
Disconnect();
return newmsgs;
}
catch (Exception e)
{
return newmsgs;
}
}
/// <summary>
/// 获取新邮件内容
/// </summary>
/// <param name="nIndex">新邮件索引 </param>
/// <returns>新邮件内容 </returns>
public MailMessage GetNewMessages(int nIndex)
{
int newcount;
MailMessage msg = new MailMessage();
try
{
newcount = GetNumberOfNewMessages();
Connect();
int n = nIndex + 1;
if (n < newcount + 1)
{
List <string> msglines = GetRawMessage(n);
string msgsubj = GetMessageSubject(msglines);
msg.Subject = msgsubj;
msg.From = new MailAddress(GetMessageFrom(msglines));
msg.Body = GetMessageBody(msglines);
}
Disconnect();
return msg;
}
catch
{
return null;
}
}
#endregion
#region Private
private bool Connect()
{
TcpClient sender = new TcpClient(POPServer, mPOPPort);
byte[] outbytes;
string input;
try
{
ns = sender.GetStream();
sr = new StreamReader(ns);
sr.ReadLine();
input = "user " + mPOPUserName + "\r\n";
outbytes = System.Text.Encoding.ASCII.GetBytes(input.ToCharArray());
ns.Write(outbytes, 0, outbytes.Length);
sr.ReadLine();
input = "pass " + mPOPPass + "\r\n";
outbytes = System.Text.Encoding.ASCII.GetBytes(input.ToCharArray());
ns.Write(outbytes, 0, outbytes.Length);
sr.ReadLine();
return true;
}
catch
{
return false;
}
}
private void Disconnect()
{
string input = "quit" + "\r\n";
Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(input.ToCharArray());
ns.Write(outbytes, 0, outbytes.Length);
ns.Close();
}
private List <string> GetRawMessage(int messagenumber)
{
Byte[] outbytes;
string input;
string line = "";
input = "retr " + messagenumber.ToString() + "\r\n";
outbytes = System.Text.Encoding.ASCII.GetBytes(input.ToCharArray());
ns.Write(outbytes, 0, outbytes.Length);
List <string> msglines = new List <string>();
do
{
line = sr.ReadLine();
msglines.Add(line);
} while (line != ".");
msglines.RemoveAt(msglines.Count - 1);
return msglines;
}
private string GetMessageSubject(List <string> msglines)
{
string[] tokens;
IEnumerator msgenum = msglines.GetEnumerator();
while (msgenum.MoveNext())
{
string line = (string)msgenum.Current;
if (line.StartsWith("Subject:"))
{
tokens = line.Split(new Char[] { ' ' });
return tokens[1].Trim();
}
}
return "None";
}
private string GetMessageFrom(List <string> msglines)
{
string[] tokens;
IEnumerator msgenum = msglines.GetEnumerator();
while (msgenum.MoveNext())
{
string line = (string)msgenum.Current;
if (line.StartsWith("From:"))
{
tokens = line.Split(new Char[] { ' <' });
return tokens[1].Trim(new Char[] { ' <', '>' });
}
}
return "None";
}
private string GetMessageBody(List <string> msglines)
{
string body = "";
string line = " ";
IEnumerator msgenum = msglines.GetEnumerator();
while (line.CompareTo("") != 0)
{
msgenum.MoveNext();
line = (string)msgenum.Current;
}
while (msgenum.MoveNext())
{
body = body + (string)msgenum.Current + "\r\n";
}
return body;
}
private void DeleteMessage(int messagenumber)
{
Byte[] outbytes;
string input;
try
{
input = "dele " + messagenumber.ToString() + "\r\n";
outbytes = System.Text.Encoding.ASCII.GetBytes(input.ToCharArray());
ns.Write(outbytes, 0, outbytes.Length);
}
catch (Exception e)
{
return;
}
}
#endregion
#endregion
}
#endregion
方法二
一个asp.net 版本的邮件接收程序,我们知道,在asp+中发送Email是见很方便的事情,可是怎么进行收取pop信件的程序呢?看来只有拿出豆腐的杀手剑了:)
首先我们来看看这个程序的代码:
pop.aspx
<%@ Assembly Name="System.Net" %>
<%@ Import Namespace="System.Net" %>
<% @Import Namespace="System.Net.Sockets" %>
<%@ Import Namespace="System.IO" %>
<script language="C#" runat=server>
protected void Page_Load(Object Src, EventArgs E){
String user="doufu"; //邮箱用户代码
String pass="asp888.net"; //邮箱用户密码
String popserver="localhost"; //pop服务器IP地址
TCPClient tcpc = new TCPClient();
if (0 == tcpc.Connect(popserver, 110))
{
//如果程序执行到这里,就表示连接Pop Server 成功
Stream s;
StreamReader sr ;
String strCmd;
Byte[] arrCmd;
String strRet;
String[] arrRet;
sr = new StreamReader(tcpc.GetStream(), Encoding.Default);
Response.Write(sr.ReadLine() + "<br>"); //mail server 的欢迎语
strRet=Logon(tcpc,user,pass);
if(JudgeString(strRet)!="+OK"){
Response.Write("对不起,没有这个用户/密码 不匹配");
return;
}
//用户和密码 匹配,下面开始 统计用户信箱的信息
//这个数组中包括了所有的返回信息
arrRet=StaticMailBox(tcpc);
if(arrRet[0]!="+OK"){
Response.Write("出错了!");
return;
}
Response.Write("当前的用户<font color=blue>" + user + "</font>的信箱中共有<font color=red>" + arrRet[1] + "</font>封,共占<font color=red>" + arrRet[2] + "</font>Byte");
//收信
arrRet=PopMail(tcpc,4);
//判断返回
if(arrRet[0]!="+OK"){
Response.Write("出错了");
}
Response.Write("邮件日期:" + arrRet[1] + "\n<br>");
Response.Write("发信人:" + arrRet[2] + "\n<br>");
Response.Write("收信人:" + arrRet[3] + "\n<br>");
Response.Write("邮件主题:" + arrRet[4] + "\n<br>");
Response.Write("邮件内容:" + arrRet[5] + "\n<br>");
//关闭Socket联结
tcpc.Close();
}
else
{
Response.Write("Could not connect to server!");
}
}
String SendPopCmd(TCPClient tcpc,String strCmd){
Byte[] arrCmd;
String strRet;
StreamReader sr;
Stream s;
s=tcpc.GetStream();
strCmd = strCmd + "\r\n";
arrCmd= Encoding.Default.GetBytes(strCmd.ToCharArray());
s=tcpc.GetStream();
s.Write(arrCmd, 0, strCmd.Length);
sr = new StreamReader(tcpc.GetStream(), Encoding.Default);
strRet=sr.ReadLine();
return strRet;
}
String Logon(TCPClient tcpc,String user,String pass){
//这个函数的功能是 对 获得联结的用户 身份进行验证
//发送 用户代码
String strRet;
strRet=SendPopCmd(tcpc,"user " + user);
strRet=SendPopCmd(tcpc,"pass " + pass);
return strRet;
}
String[] StaticMailBox(TCPClient tcpc){
String strRet;
strRet=SendPopCmd(tcpc,"stat");
if(JudgeString(strRet)!="+OK"){
return "-ERR -ERR".Split(" ".ToCharArray());
}
String[] arrRet=strRet.Split(" ".ToCharArray());
return arrRet;
}
String JudgeString(String strCheck){
if(strCheck.Substring(0,3)!="+OK"){
return "-ERR";
}
else
return "+OK";
}
String[] PopMail(TCPClient tcpc,int i){
String strRet;
bool strBody=false;
String[] arrRet =new String[10];
String[] arrTemp;
strRet=SendPopCmd(tcpc,"retr " + i.ToString());
if(JudgeString(strRet)!="+OK"){
//表示没有这个信件 或者 其他的错误
return "-ERR -ERR".Split(" ".ToCharArray());
}
StreamReader sr;
sr = new StreamReader(tcpc.GetStream(), Encoding.Default);
Response.Write("\n<BR>");
Response.Write("<font color=red>\n<BR>");
while (sr.Peek()!=46)
{
//呵呵,不知道 为什么 非要是 46 才可以!
strRet=sr.ReadLine();
arrTemp=strRet.Split(":".ToCharArray());
if(strRet=="")
strBody=true; //现在开始接收 Body 的信息
if(arrTemp[0]=="Date"){
arrRet[1]=arrTemp[1]; //信件的发送日期
}
if(arrTemp[0]=="From")
arrRet[2]=arrTemp[1]; //发信人
if(arrTemp[0]=="To")
arrRet[3]=arrTemp[1]; //收信人
if(arrTemp[0]=="Subject")
arrRet[4]=arrTemp[1]; //主题
if(strBody){
arrRet[5]=arrRet[5] + strRet + "\n";
}
}
arrRet[0]="+OK";
return arrRet;
}
</script>
好了大家通过这个程序,首先可以了解到pop(Post Ofice Protocal)协议,其次可以加深对asp.net的socket 程序的
理解,还可以通过这个程序接收ISP提供的没有Web方式收取邮件的程序对ISP的信箱进行管理。