求一个 C#接收邮件的类, 里面有邮件解码的,大家帮帮忙。
谢谢!
谢谢!
解决方案 »
- 超链接asp:HyperLink显示在网页上不是链接,和普通文字一样,怎么解决?
- datalist如何读取某一列的值?在线等
- 在datagrid中放入checkbox如何进行选择性的删除?
- 救命。。急需解决问题。。。如何获得div 中的所有内容
- _______________有点头晕,页面跳转的小问题_______________
- 如何用c#实现跟着网页滚动的两边广告条!
- 关于showModaldialog的问题
- 主细表的问题????????????????????????????????????
- 提交到另一页的问题~icyer,zgh_ms([微软] 百变金刚)帮忙看看!
- 希望在datagrid中有一列为检查框的问题
- |zyciis| 如何移动控件的前后顺序,谢谢 有代码
- login控件是如何验证用户名,密码登录的呀?
http://www.eit.name/blog/read.php?265
using System;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
namespace PopEngine
{
internal class AsyncState
{
public System.Net.Sockets.NetworkStream Stream;
public System.Net.Sockets.TcpClient Client;
public System.IO.StreamWriter Writer;
public string Data = "";
public byte[] Buffer;
public int RemainingBytes = 0;
public System.IO.MemoryStream MailStream;
public AsyncState()
{
Buffer = new byte[1000];
}
}
/// <summary>
/// Zusammenfassung f黵 PopHandler.
/// </summary>
public class PopHandler
{
private TcpClient Talker;
private Thread WaitThread;
private AsyncState State;
private ArrayList MailList;
private object tLock = new object();
private DateTime LastHeartBeat;
public PopHandler(string Servername, int Port, string UserName, string Password)
{
Talker = new TcpClient(Servername,Port);
State = new AsyncState();
State.Client = Talker;
State.Stream = Talker.GetStream();
State.Writer = new System.IO.StreamWriter(State.Stream);
BeginWait();
StartLFRead();
WaitToEnd();
if (State.Data.StartsWith("+"))
{
State.Data = "";
LogOn(UserName, Password);
}
else
{
Exception up = new Exception("Error! Connect to Server Failed!" + State.Data);
State.Data = "";
throw up;
}
} private void WaitToEnd()
{
bool WaitOK = true;
do
{
DateTime t = DateTime.Now;
TimeSpan s = t.Subtract(LastHeartBeat);
if (s.TotalSeconds > 10)
{
if (Monitor.TryEnter(tLock,100))
{
Monitor.Pulse(tLock);
Monitor.Exit(tLock);
}
else
{
WaitThread.Abort();
}
WaitOK = false;
}
}
while(!WaitThread.Join(1000));
if (!WaitOK)
{
Exception up = new Exception("Timeout on Server");
throw up;
}
}
public void DeleteAllMails()
{
if (MailList != null)
{
for (int i = MailList.Count-1; i> -1; i--)
{
DeleteMail(i);
}
}
else
{
InvalidOperationException up = new InvalidOperationException("Get Maillist first!");
throw up;
}
}
public void DeleteMail(int Index)
{
if (MailList != null)
{
if (MailList.Count > Index & Index > -1)
{
ExecuteCommand(string.Format("DELE {0}",((string[])MailList[Index])[0]));
MailList.RemoveAt(Index);
}
else
{
IndexOutOfRangeException up = new IndexOutOfRangeException("Error! Mailindex out of range");
throw up;
}
}
else
{
InvalidOperationException up = new InvalidOperationException("Get List of Mails first!");
throw up;
}
} public string[] GetList()
{
string RV;
string[] RetVal = null;
string[] tmpVal;
RV = ExecuteCommand("LIST",true);
if (!RV.EndsWith("\r\n.\r\n"))
{
BeginWait();
State.MailStream = new System.IO.MemoryStream();
State.MailStream.Write(System.Text.Encoding.Default.GetBytes(RV),0,RV.Length);
StartEndMailRead();
WaitToEnd();
RV = State.Data;
State.Data = "";
}
tmpVal = RV.Split(new char[]{'\n'});
if (tmpVal.Length -3 > 0)
{
RetVal = new string[tmpVal.Length-3];
MailList = new ArrayList();
for (int i = 0; i< RetVal.Length; i++)
{
RetVal[i] = tmpVal[i+1].Split(' ')[1].Split('\r')[0];
MailList.Add(tmpVal[i+1].Substring(0,tmpVal[i+1].Length-1).Split(' '));
}
}
return RetVal;
} public PopMail GetMailHeader(int Index)
{
PopMail RetVal;
if (MailList != null)
{
if (MailList.Count > Index & Index > -1)
{
State.Writer.WriteLine("Top {0} 0",((string[])MailList[Index])[0]);
State.Writer.Flush();
//ExecuteCommand(string.Format("Retr {0}",((string[])MailList[Index])[0]));
State.MailStream = new System.IO.MemoryStream();
BeginWait();
StartEndMailRead(int.Parse(((string[])MailList[Index])[1]));
WaitToEnd();
RetVal = new PopMail(State.Data.Substring(State.Data.IndexOf("\r\n")+2));
State.Data = "";
}
else
{
IndexOutOfRangeException up = new IndexOutOfRangeException("Mailindex invalid");
throw up;
}
}
else
{
InvalidOperationException up = new InvalidOperationException("Get Maillist first!");
throw up;
}
return RetVal;
}
public PopMail GetMail(int Index)
{
PopMail RetVal;
if (MailList != null)
{
if (MailList.Count > Index & Index > -1)
{
State.Writer.WriteLine("Retr {0}",((string[])MailList[Index])[0]);
State.Writer.Flush();
//ExecuteCommand(string.Format("Retr {0}",((string[])MailList[Index])[0]));
State.MailStream = new System.IO.MemoryStream();
BeginWait();
StartEndMailRead(int.Parse(((string[])MailList[Index])[1]));
WaitToEnd();
RetVal = new PopMail(State.Data.Substring(State.Data.IndexOf("\r\n")+2));
State.Data = "";
}
else
{
IndexOutOfRangeException up = new IndexOutOfRangeException("Mailindex invalid");
throw up;
}
}
else
{
InvalidOperationException up = new InvalidOperationException("Get Maillist first!");
throw up;
}
return RetVal;
}
public void Disconnect()
{
ExecuteCommand("QUIT");
State.Client.Close();
State.Stream.Close();
State.Writer.Close();
}
private void StartEndMailRead(int Size)
{
LastHeartBeat = DateTime.Now;
State.RemainingBytes = Size;
State.Buffer = new byte[1000];
State.Stream.BeginRead(State.Buffer,0,1000,new AsyncCallback(ReadToEndMail),State);
}
private void StartEndMailRead()
{
LastHeartBeat = DateTime.Now;
State.RemainingBytes = 0;
State.Buffer = new byte[1000];
State.Stream.BeginRead(State.Buffer,0,State.Buffer.Length,new AsyncCallback(ReadToEndMail),State);
}
private void ReadToEndMail(IAsyncResult Result)
{
try
{
AsyncState stt = (AsyncState)Result.AsyncState;
int Len = stt.Stream.EndRead(Result);
if (Len > 0)
{
LastHeartBeat = DateTime.Now;
System.Diagnostics.Debug.Write(Len.ToString() + "\r\n");
stt.MailStream.Write(stt.Buffer,0,Len);
stt.RemainingBytes -= Len;
stt.Buffer = new byte[1000];
/*else
{
stt.MailStream.Position = 0;
MailReader = new System.IO.StreamReader(stt.MailStream,System.Text.Encoding.Default);
stt.Data = MailReader.ReadToEnd();
}*/
}
if (stt.MailStream.Position >=5)
{
stt.MailStream.Position -=5;
byte[] f = new byte[5];
stt.MailStream.Read(f,0,5);
string s = System.Text.Encoding.Default.GetString(f,0,5);
//if (System.Text.Encoding.Default.GetString(f,0,5) == "\r\n.\r\n")
if (s.EndsWith("\r\n.\r\n"))
{
不知能不能解码
在
http://www.mybuffet.cn/articleid.aspx?article_id=220
能找到源码http://www.mybuffet.cn
using System.Net.Sockets;
using System.Net;
using System.Security.Cryptography;
using System.IO;
// 类名:Pop3
// 功能:接收电子邮件namespace ZTSX.Email
{
/// <summary>
/// Pop3 的摘要说明。
/// </summary>
public class Pop3
{
private string mstrHost = null; //主机名称或IP地址
private int mintPort = 110; //主机的端口号(默认为110)
private TcpClient mtcpClient = null; //客户端
private NetworkStream mnetStream = null; //网络基础数据流
private StreamReader m_stmReader = null; //读取字节流
private string mstrStatMessage = null; //执行STAT命令后得到的消息(从中得到邮件数)/// <summary>
/// 构造函数
/// </summary>
/// <res>一个邮件接收对象</res>
public Pop3()
{
}/// <summary>
/// 构造函数
/// </summary>
/// <param name="host">主机名称或IP地址</param>
public Pop3(string host)
{
mstrHost = host;
}/// <summary>
/// 构造函数
/// </summary>
/// <param name="host">主机名称或IP地址</param>
/// <param name="port">主机的端口号</param>
/// <res>一个邮件接收对象</res>
public Pop3(string host,int port)
{
mstrHost = host;
mintPort = port;
}#region 属性/// <summary>
/// 主机名称或IP地址
/// </summary>
/// <res>主机名称或IP地址</res>
public string HostName
{
get{return mstrHost;}
set{mstrHost = value;}
}/// <summary>
/// 主机的端口号
/// </summary>
/// <res>主机的端口号</res>
public int Port
{
get{return mintPort;}
set{mintPort = value;}
}#endregion#region 私有方法/// <summary>
/// 向网络访问的基础数据流中写数据(发送命令码)
/// </summary>
/// <param name="netStream">可以用于网络访问的基础数据流</param>
/// <param name="command">命令行</param>
/// <res>向网络访问的基础数据流中写数据(发送命令码)</res>
private void WriteToNetStream(ref NetworkStream netStream,String command)
{
string strToSend = command + "\r\n";
byte[] arrayToSend = System.Text.Encoding.ASCII.GetBytes(strToSend.ToCharArray());
netStream.Write(arrayToSend,0,arrayToSend.Length);
}/// <summary>
/// 检查命令行结果是否正确
/// </summary>
/// <param name="message">命令行的执行结果</param>
/// <param name="check">正确标志</param>
/// <returns>
/// 类型:布尔
/// 内容:true表示没有错误,false为有错误
/// </returns>
/// <res>检查命令行结果是否有错误</res>
private bool CheckCorrect(string message,string check)
{
if(message.IndexOf(check) == -1)
return false;
else
return true;
}/// <summary>
/// 邮箱中的未读邮件数
/// </summary>
/// <param name="message">执行完LIST命令后的结果</param>
/// <returns>
/// 类型:整型
/// 内容:邮箱中的未读邮件数
/// </returns>
/// <res>邮箱中的未读邮件数</res>
private int GetMailNumber(string message)
{
string[] strMessage = message.Split(' ');
return Int32.Parse(strMessage[1]);
}/// <summary>
/// 得到经过解码后的邮件的内容
/// </summary>
/// <param name="encodingContent">解码前的邮件的内容</param>
/// <returns>
/// 类型:字符串
/// 内容:解码后的邮件的内容
/// </returns>
/// <res>得到解码后的邮件的内容</res>
private string GetDecodeMailContent(string encodingContent)
{
string strContent = encodingContent.Trim();
string strEncode = null; int iStart = strContent.IndexOf("Base64");
if(iStart == -1)
throw new Pop3Exception("邮件内容不是Base64编码,请检查");
else
{
strEncode = strContent.Substring(iStart + 6,strContent.Length - iStart - 6);
try
{
return SX.Encode.TransformToString(strEncode);
}
catch(SX.EncodeException exc)
{
throw new Pop3Exception(exc.Message);
}
}
}#endregion/// <summary>
/// 与主机建立连接
/// </summary>
/// <returns>
/// 类型:布尔
/// 内容:连接结果(true为连接成功,false为连接失败)
/// </returns>
/// <res>与主机建立连接</res>
public bool Connect()
{
if(mstrHost == null)
throw new Exception("请提供SMTP主机名称或IP地址!");
if(mintPort == 0)
throw new Exception("请提供SMTP主机的端口号");
try
{
mtcpClient = new TcpClient(mstrHost,mintPort);
mnetStream = mtcpClient.GetStream();
m_stmReader = new StreamReader(mtcpClient.GetStream()); string strMessage = m_stmReader.ReadLine();
if(CheckCorrect(strMessage,"+OK") == true)
return true;
else
return false;
}
catch(SocketException exc)
{
throw new Pop3Exception(exc.ToString());
}
catch(NullReferenceException exc)
{
throw new Pop3Exception(exc.ToString());
}
}#region Pop3命令/// <summary>
/// 执行Pop3命令,并检查执行的结果
/// </summary>
/// <param name="command">Pop3命令行</param>
/// <returns>
/// 类型:字符串
/// 内容:Pop3命令的执行结果
/// </returns>
private string ExecuteCommand(string command)
{
string strMessage = null; //执行Pop3命令后返回的消息 try
{
//发送命令
WriteToNetStream(ref mnetStream,command); //读取多行
if(command.Substring(0,4).Equals("LIST") || command.Substring(0,4).Equals("RETR") || command.Substring(0,4).Equals("UIDL")) //记录STAT后的消息(其中包含邮件数)
{
strMessage = ReadMultiLine(); if(command.Equals("LIST")) //记录LIST后的消息(其中包含邮件数)
mstrStatMessage = strMessage;
}
//读取单行
else
strMessage = m_stmReader.ReadLine(); //判断执行结果是否正确
if(CheckCorrect(strMessage,"+OK"))
return strMessage;
else
return "Error";
}
catch(IOException exc)
{
throw new Pop3Exception(exc.ToString());
}
}/// <summary>
/// 在Pop3命令中,LIST、RETR和UIDL命令的结果要返回多行,以点号(.)结尾,
/// 所以如果想得到正确的结果,必须读取多行
/// </summary>
/// <returns>
/// 类型:字符串
/// 内容:执行Pop3命令后的结果
/// </returns>
private string ReadMultiLine()
{
string strMessage = m_stmReader.ReadLine();
string strTemp = null;
while(strMessage != ".")
{
strTemp = strTemp + strMessage;
strMessage = m_stmReader.ReadLine();
}
return strTemp;
}//USER命令
private string USER(string user)
{
return ExecuteCommand("USER " + user) + "\r\n";
}//PASS命令
private string PASS(string password)
{
return ExecuteCommand("PASS " + password) + "\r\n";
}//LIST命令
private string LIST()
{
return ExecuteCommand("LIST") + "\r\n";
}//UIDL命令
private string UIDL()
{
return ExecuteCommand("UIDL") + "\r\n";
}//NOOP命令
private string NOOP()
{
return ExecuteCommand("NOOP") + "\r\n";
}//STAT命令
private string STAT()
{
return ExecuteCommand("STAT") + "\r\n";
}//RETR命令
private string RETR(int number)
{
return ExecuteCommand("RETR " + number.ToString()) + "\r\n";
}//DELE命令
private string DELE(int number)
{
return ExecuteCommand("DELE " + number.ToString()) + "\r\n";
}//QUIT命令
private void Quit()
{
WriteToNetStream(ref mnetStream,"QUIT");
}/// <summary>
/// 收取邮件
/// </summary>
/// <param name="user">用户名</param>
/// <param name="password">口令</param>
/// <returns>
/// 类型:字符串数组
/// 内容:解码前的邮件内容
/// </returns>
private string[] ReceiveMail(string user,string password)
{
int iMailNumber = 0; //邮件数 if(USER(user).Equals("Error"))
throw new Pop3Exception("用户名不正确!");
if(PASS(password).Equals("Error"))
throw new Pop3Exception("用户口令不正确!");
if(STAT().Equals("Error"))
throw new Pop3Exception("准备接收邮件时发生错误!");
if(LIST().Equals("Error"))
throw new Pop3Exception("得到邮件列表时发生错误!"); try
{
iMailNumber = GetMailNumber(mstrStatMessage); //没有新邮件
if(iMailNumber == 0)
return null;
else
{
string[] strMailContent = new string[iMailNumber]; for(int i = 1 ; i <= iMailNumber ; i++)
{
//读取邮件内容
strMailContent[i - 1] = GetDecodeMailContent(RETR(i));
}
return strMailContent;
}
}
catch(Pop3Exception exc)
{
throw new Pop3Exception(exc.ToString());
}
}#endregion
/// <summary>
/// 收取邮件
/// </summary>
/// <param name="user">用户名</param>
/// <param name="password">口令</param>
/// <returns>
/// 类型:字符串数组
/// 内容:解码前的邮件内容
/// </returns>
///<res>收取邮箱中的未读邮件</res>
public string[] Receive(string user,string password)
{
try
{
return ReceiveMail(user,password);
}
catch(Pop3Exception exc)
{
throw new Pop3Exception(exc.ToString());
}
}/// <summary>
/// 断开所有与服务器的会话
/// </summary>
/// <res>断开所有与服务器的会话</res>
public void DisConnect()
{
try
{
Quit();
if(m_stmReader != null)
m_stmReader.Close();
if(mnetStream != null)
mnetStream.Close();
if(mtcpClient != null)
mtcpClient.Close();
}
catch(SocketException exc)
{
throw new Pop3Exception(exc.ToString());
}
}/// <summary>
/// 删除邮件
/// </summary>
/// <param name="number">邮件号</param>
public void DeleteMail(int number)
{
//删除邮件
int iMailNumber = number + 1;
if(DELE(iMailNumber).Equals("Error"))
throw new Pop3Exception("删除第" + iMailNumber.ToString() + "时出现错误!");
}}
}
string strUserName = "";//用户名
string strPassWord = ""; //密码
StringBuilder strBuildeMailMessage = new StringBuilder();
int numberOfBytesRead = 0;
int length = 1024 * 10;
byte[] buttfer = new byte[length];
TcpClient tp = new TcpClient(strServerName, 110);
tp.ReceiveTimeout = 1000 * 300;
NetworkStream ns = tp.GetStream();
ns.ReadTimeout = 1000 * 300;
ns.Read(buttfer, 0, buttfer.Length); byte[] outbytes = System.Text.Encoding.ASCII.GetBytes("user " + strUserName + "\r\n");
ns.Write(outbytes, 0, outbytes.Length);
numberOfBytesRead = ns.Read(buttfer, 0, buttfer.Length);
strBuildeMailMessage.Append(System.Text.Encoding.ASCII.GetString(buttfer, 0, numberOfBytesRead)); strBuildeMailMessage = new StringBuilder();
outbytes = System.Text.Encoding.ASCII.GetBytes("pass " + strPassWord + "\r\n");
ns.Write(outbytes, 0, outbytes.Length);
numberOfBytesRead = ns.Read(buttfer, 0, buttfer.Length);
strBuildeMailMessage.Append(System.Text.Encoding.ASCII.GetString(buttfer, 0, numberOfBytesRead)); Regex re = new Regex(@"(?<=has\s+)[\d]+(?=\s+messages)");
int num = int.Parse(re.Match(strBuildeMailMessage.ToString()).Value.Trim()); List<string> emailList = new List<string>();
for (int i = 1; i <= num; i++)
{
strBuildeMailMessage = new StringBuilder();
outbytes = System.Text.Encoding.ASCII.GetBytes("retr " + i.ToString() + "\r\n");
ns.Write(outbytes, 0, outbytes.Length); Thread.Sleep(100);
do
{
numberOfBytesRead = ns.Read(buttfer, 0, buttfer.Length);
strBuildeMailMessage.Append(System.Text.Encoding.ASCII.GetString(buttfer, 0, numberOfBytesRead));
Thread.Sleep(100);
} while (ns.DataAvailable);
emailList.Add(strBuildeMailMessage.ToString());
}
outbytes = System.Text.Encoding.ASCII.GetBytes("quit\r\n");
ns.Write(outbytes, 0, outbytes.Length);