POP3 郵件檢查

1 篇文章 / 0 new
author
POP3 郵件檢查
public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }
 
    private void btnCheck_Click(object sender, EventArgs e)
    {
        if (this.tbPassword.Text == "" | this.tbPort.Text == "" | this.tbServer.Text == ""
            | this.tbUser.Text == "" | this.tbTime.Text == "")
        {
            MessageBox.Show("請設定郵件資料");
            return;
        }
        TcpClient client = new TcpClient();
        try
        {
            client.Connect(this.tbServer.Text, Int32.Parse(this.tbPort.Text));
        }
        catch (Exception err)
        {
            MessageBox.Show("無法連接POP3:"+err.Message);
        }
        try
        {
            NetworkStream stream = client.GetStream();
            if (stream == null)
            {
                throw new Exception("沒有郵件訊息");
            }
            string mailMes = readFromNetStream(ref stream);//取得郵件訊息
            checkForError(mailMes);
            //送出帳號
            writeToNetStream(ref stream, "USER " + this.tbUser.Text);
            mailMes = readFromNetStream(ref stream);
            checkForError(mailMes);
            //送出密碼
            writeToNetStream(ref stream, "PASS " + this.tbPassword.Text);
            mailMes = readFromNetStream(ref stream);//取得郵件訊息
            checkForError(mailMes);
            //送出統計請求
            writeToNetStream(ref stream, "STAT");
            mailMes = readFromNetStream(ref stream);//取得郵件訊息
            checkForError(mailMes);
            //處理訊息
            string[] total = mailMes.Split(new char[] { ' ' });
            int count = Int32.Parse(total[1]);//郵件數量
            int totalSize = Int32.Parse(total[2]);//總大小
            this.Text = "郵件通知:"+count.ToString()+"/"+totalSize.ToString();
            stream.Close();
            client.Close();
        }
        catch (Exception err)
        {
            MessageBox.Show("檢查錯誤:"+err.Message);
        }
    }
    private void writeToNetStream(ref NetworkStream stream, string comm)
    {   //處理命令
        string sendComm = comm + "\r\n";
        Byte[] send = Encoding.ASCII.GetBytes(sendComm.ToCharArray());
        stream.Write(send, 0, send.Length);
    }
    private String readFromNetStream(ref NetworkStream stream)
    {   //讀取郵件訊息
        StringBuilder receive = new StringBuilder();
        StreamReader reader = new StreamReader(stream);
        String line = reader.ReadLine();
        while (line == null || line.Length == 0)
        {
            line = reader.ReadLine();
        }
        receive.Append(line);
        if (reader.Peek() != -1)
        {
            while ((line = reader.ReadLine()) != null)
            {
                receive.Append(line);
            }
        }
        return receive.ToString();
    }
    private void checkForError(string mess)
    {
        if (mess.IndexOf("+OK")==-1)
            throw new Exception("Error:"+mess);
    }
}
Free Web Hosting