享受自由与创造的乐趣!

I LOVE THIS GAME

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::
Mail.rar

/* 
 * 基于 System.Web.Mail  的邮件发送和接收类
*/


using System;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Web.Mail;
using System.Text;

namespace Mail
{
    
#region "邮件接收类"
    
/// <summary>
    
/// 邮件接收类
    
/// </summary>

    public class POP3
    
{
        
string POPServer;
        
string user;
        
string pwd;
        NetworkStream ns;
        StreamReader sr;

        
public POP3(){}

        

        
/// <summary>
        
/// POP3
        
/// </summary>
        
/// <param name="server">POP3服务器名称</param>
        
/// <param name="_user">用户名</param>
        
/// <param name="_pwd">用户密码</param>

        public POP3(string server, string _user, string _pwd)
        
{
            POPServer 
= server;
            user 
= _user;
            pwd 
= _pwd;
        }


        
private bool Connect()
        
{
            TcpClient sender 
= new TcpClient(POPServer,110);
            
byte[] outbytes;
            
string input;

            
try
            
{
                ns 
= sender.GetStream();
                sr 
= new StreamReader(ns);

                sr.ReadLine();
                input 
= "user " + user + "\r\n";
                outbytes 
= System.Text.Encoding.ASCII.GetBytes(input.ToCharArray());
                ns.Write(outbytes,
0,outbytes.Length) ;
                sr.ReadLine();
            
                input 
= "pass " + pwd + "\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();
        }


        
/// <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 ArrayList GetNewMessages(string subj)
        
{

            
int newcount;
            ArrayList newmsgs 
= new ArrayList();

            
try
            
{
                newcount 
= GetNumberOfNewMessages();
                Connect();

                
for(int n=1; n<newcount+1; n++)
                
{
                    ArrayList msglines 
= GetRawMessage(n);
                    
string msgsubj = GetMessageSubject(msglines);
                    
if(msgsubj.CompareTo(subj) == 0)
                    
{
                        System.Web.Mail.MailMessage msg 
= new MailMessage();
                        msg.Subject 
= msgsubj;
                        msg.From 
= 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;
            System.Web.Mail.MailMessage msg 
= new MailMessage();

            
try
            
{
                newcount 
= GetNumberOfNewMessages();
                Connect();
                
int n = nIndex+1;

                
if(n<newcount+1)
                
{
                    ArrayList msglines 
= GetRawMessage(n);
                    
string msgsubj = GetMessageSubject(msglines);
                
                    
                    msg.Subject 
= msgsubj;
                    msg.From 
= GetMessageFrom(msglines);
                    msg.Body 
= GetMessageBody(msglines);
                }


                Disconnect();
                
return msg;
            }

            
catch
            
{
                
return null;
            }

        }

        
private ArrayList 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);

            ArrayList msglines 
= new ArrayList();
            
do
            
{
                line 
= sr.ReadLine();
                msglines.Add(line);
            }
 while (line != ".");
            msglines.RemoveAt(msglines.Count
-1);

            
return msglines;
        }

        
private string GetMessageSubject(ArrayList 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 (ArrayList 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(ArrayList 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


    
#region "邮件发送类"

    
/// <summary>
    
/// 邮件发送类
    
/// </summary>

    public class SMTP
    
{
        
public SMTP(){}
        
        
/// <summary>
        
/// 发送邮件
        
/// </summary>
        
/// <param name="strSmtpServer">SMTP服务器名称</param>
        
/// <param name="nPort">端口号</param>
        
/// <param name="strSend">发件人名称</param>
        
/// <param name="strReceive">收件人名称</param>
        
/// <param name="strSubject">邮件主题</param>
        
/// <param name="strContent">邮件内容</param>
        
/// <returns>指示邮件是否发送成功</returns>

        public bool Send(string strSmtpServer,int nPort,string strSend,string strReceive
            ,
string strSubject,string strContent)
        
{
              
            
string smtpserver=strSmtpServer;// smtp服务器的IP地址
            TcpClient tcpc = new TcpClient();
            
try
            
{
                tcpc.Connect(smtpserver, nPort);
                StreamReader sr ;
                
string strCmd;
                sr 
= new StreamReader(tcpc.GetStream(),Encoding.Default);
                
//服务器连接成功以后,首先向服务器发送HeLlo命令
                strCmd="HELO shaozhd";
                SenSmtpCmd(tcpc,strCmd);
                
//然后向服务器发送信件的成员的信箱
                strCmd="mail from:"+ strSend;
                SenSmtpCmd(tcpc,strCmd);
                
//向服务器发送收件人的信箱
                strCmd="rcpt to:" + strReceive;
                SenSmtpCmd(tcpc,strCmd);
                
//所有的准备工作都已经作好了,下面开始进行邮件的部分
                strCmd="data";
                SenSmtpCmd(tcpc,strCmd);
                
//邮件内容
                strCmd="Date: 1234567\r\n";
                strCmd
=strCmd+"From: " + strSend +"\r\n";
                strCmd
=strCmd+"To: " + strReceive +"\r\n";
                strCmd
=strCmd+"Subject: " + strSubject +"\r\n\r\n";
                strCmd
=strCmd + strContent +"\r\n\r\n";
                SenSmtpCmd(tcpc,strCmd);
                strCmd
="\r\n.\r\n";
                SenSmtpCmd(tcpc,strCmd);
                
//最后 关闭与smtp 服务器的连接
          tcpc.Close();
                
return true;
             }

            
catch
            
{
                
return false;
            }

        }

        
void SenSmtpCmd(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;
        }


        
/// <summary>
        
/// 发送邮件(加入身份验证信息)
        
/// </summary>
        
/// <param name="strSmtpServer">SMTP服务器名称</param>
        
/// <param name="strSendName">指定发件人名称</param>
        
/// <param name="strReceive">指定收件人地址</param>
        
/// <param name="strUserName">指定邮件用户名称</param>
        
/// <param name="strPass">指定邮件用户密码</param>
        
/// <param name="strSubject">指定邮件主题</param>
        
/// <param name="strContent">指定邮件内容</param>
        
/// <param name="strPriority">指定邮件优先级("High"为高,"Low"为低,默认为"Normal"常规</param>
        
/// <param name="strBodyFormat">指定邮件格式("Text" Or "Html"),默认为"Html"</param>
        
/// <param name="strFileName">指定附件路径</param>
        
/// <returns>指示邮件是否发送成功</returns>

        public bool Send(string strSmtpServer,string strSendName,string strReceive
            ,
string strUserName,string strPass, string strSubject,string strContent
            ,
string strPriority,string strBodyFormat,string strFileName)
        
{
            MailMessage m 
= new MailMessage();
            m.From 
= strSendName;
            m.To 
= strReceive;
            m.Subject 
= strSubject;
            m.Body 
= strContent;
            
//优先级
            switch(strPriority)
            
{
                
case "High":
                    m.Priority 
= MailPriority.High;
                    
break;
                
case "Low":
                    m.Priority 
= MailPriority.Low;
                    
break;
                
default:
                    m.Priority 
= MailPriority.Normal;
                    
break;
            }

            
//格式
            switch(strPriority)
            
{
                
case "Text":
                    m.BodyFormat 
= MailFormat.Text;
                    
break;
                
default:
                    m.BodyFormat 
= MailFormat.Html;
                    
break;
            }

            
//以下设置服务器
            if(strSmtpServer!="")
            
{
                SmtpMail.SmtpServer 
= strSmtpServer;
                
//以下代码适用于Framework1.1以上版本。
                m.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",
                    
"1");    //basic authentication
                m.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername",
                    strUserName); 
//set your username here
                m.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword",
                    strPass);    
//set your password here
            }

            
//以下处理附件 
            if(strFileName!="")
                m.Attachments.Add(
new MailAttachment(strFileName));
            
try
            
{
                SmtpMail.Send(m);
                
return true;
            }

            
catch (Exception e)
            
{
                
return false;
            }

        }

    }

    
#endregion


}


posted on 2005-09-02 22:15  helloworld84  阅读(2885)  评论(3)    收藏  举报