1. 程式人生 > >電子郵件的傳送與接收例項

電子郵件的傳送與接收例項

這個就不寫很多不同類的屬性和方法了。其中涉及的類有MailMessage類,SmtpClient類

其實可有還有相關的Attachment類:表示電子郵件的附件

以下是我看的一本書中的例項,我也就直接貼例項程式碼了:

一共三個窗體:Form1,frmSend,frmReceive

首先是Form1窗體:


後臺程式碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EmailSendAndReceive
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void 郵件傳送ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmSend frmsend = new frmSend();
            frmsend.MdiParent = this;
            frmsend.Show();
        }

        private void 郵件接收ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmReceive frmreceive = new frmReceive();
            frmreceive.MdiParent = this;
            frmreceive.Show();
        }
    }
}


其次是郵件傳送窗體:


後臺程式碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;

namespace EmailSendAndReceive
{
    public partial class frmSend : Form
    {
        public frmSend()
        {
            InitializeComponent();
        }
        //對郵件內容進行編碼
        public static string Base64Encode(string str)
        {
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(str));
        }
        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                MailAddress from = new MailAddress(txtSend.Text);   //設定郵件傳送人
                MailAddress to = new MailAddress(txtTo.Text);       //設定郵件接收人
                MailMessage message = new MailMessage(from, to);    //例項化一個MaileMessage類物件
                message.Subject = Base64Encode(txtSubject.Text);    //設定傳送郵件的主題
                message.Body = Base64Encode(txtContent.Text);       //設定傳送郵件的內容
                //例項化SmtpClient郵件傳送類物件
                SmtpClient client = new SmtpClient(txtServer.Text, Convert.ToInt32(txtPort.Text));
                //設定用於驗證發件人身份的憑據
                client.Credentials = new System.Net.NetworkCredential(txtName.Text, txtPwd.Text);
                //傳送郵件
                client.Send(message);
                MessageBox.Show("傳送成功");
            }
            catch
            {
                MessageBox.Show("傳送失敗!");
            }
        }
    }
}

最後是郵件接收窗體:


後臺程式碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace EmailSendAndReceive
{
    public partial class frmReceive : Form
    {
        public frmReceive()
        {
            InitializeComponent();
        }
        public static string strserver;     //儲存郵件伺服器
        public static string pwd;           //儲存使用者登入郵箱的密碼
        public static int k;                //儲存郵件數目
        public static TcpClient tcpclient;  //例項化TcpClient物件,用來建立客戶端連線
        public static StreamReader sreader; //通過流讀取郵件內容
        public static string strRet;        //儲存郵件內容
        //向伺服器傳送命令
        private string SendPopCmd(TcpClient tcpclient, string strCmd)
        {
            Byte[] arrCmd;
            string strRet;
            Stream stream;
            stream = tcpclient.GetStream();
            strCmd = strCmd + "\r\n";
            arrCmd = Encoding.Default.GetBytes(strCmd.ToCharArray());
            stream.Write(arrCmd, 0, strCmd.Length);
            strRet = sreader.ReadLine();
            return strRet;
        }
        //該方法用來對獲得連線的使用者身份進行驗證
        private string Logon(TcpClient tcpclient, string user, string pass)
        {
            string strRet;                                   //儲存使用者登入資訊
            strRet = SendPopCmd(tcpclient, "user " + user); //向登入伺服器傳送使用者名稱
            strRet = SendPopCmd(tcpclient, "pass " + pass);  //想登入伺服器傳送密碼
            return strRet;
        }
        //獲取登入郵箱的各種資訊
        private string[] StaticMailBox(TcpClient tcpclient)
        {
            string strRet;
            strRet = SendPopCmd(tcpclient, "stat");          //向伺服器傳送資訊返回郵箱的統計資料
            if (JudgeString(strRet) != "+OK")
            {
                return "-ERR -ERR".Split(" ".ToCharArray());
            }
            else
            {
                string[] arrRet = strRet.Split(" ".ToCharArray());
                return arrRet;
            }
        }
        //判斷返回的字串資訊,如果是“+OK”,證明登入成功,否則登入失敗
        private string JudgeString(string strCheck)
        {
            if (strCheck.Substring(0, 3) != "+OK")
            {
                return "-ERR";
            }
            else
                return "+OK";
        }
        //根據輸入的郵件編號讀取郵件資訊
        private string[] PopMail(TcpClient tcpclient, int i)
        {
            string strRet;
            string[] arrRet = new string[20];
            bool strBody = false;
            string[] arrTemp;
            //獲取由引數標識的郵件的全部文字
            strRet = SendPopCmd(tcpclient, "retr " + i.ToString());
            if (JudgeString(strRet) != "+OK")
            {
                return "-ERR -ERR".Split(" ".ToCharArray());
            }
            arrRet[0] = "+OK";
            while (sreader.Peek() != 46)
            {
                strRet = sreader.ReadLine();
                arrTemp = strRet.Split(":".ToCharArray());
                if (strRet == "")
                    strBody = true;                     //現在開始接收 Body 的資訊
                if (arrTemp[0].ToLower() == "date")
                    arrRet[1] = arrTemp[1];             //信件的傳送日期
                if (arrTemp[0].ToLower() == "from")
                    arrRet[2] = (arrTemp[1].Substring(arrTemp[1].LastIndexOf("<") + 1)).Replace(">", " ");  //發信人
                if (arrTemp[0].ToLower() == "to")
                    arrRet[3] = (arrTemp[1].Substring(arrTemp[1].LastIndexOf("<") + 1)).Replace(">", " ");  //收信人
                if (arrTemp[0].ToLower() == "subject")
                    arrRet[4] = arrTemp[1].ToString();  //主題
                if (strBody)
                    arrRet[5] = arrRet[5] + strRet + "\n";
            }
            return arrRet;
        }
        //對讀取的郵件內容進行Base64編碼
        public static string Base64Decode(string str)
        {
            return Encoding.UTF8.GetString(Convert.FromBase64String(str));
        }
        //“登入”按鈕事件
        private void btnLogin_Click(object sender, EventArgs e)
        {
            string user = txtMail.Text;
            string pass = txtPwd.Text;
            string[] arrRet;
            pwd = pass;
            strserver = txtPOP.Text;
            tcpclient = new TcpClient();
            try
            {
                tcpclient.Connect(strserver, 110);       //連線遠端主機
                //初始化StreamReader物件,以便以流的形式讀取遠端主機中的內容
                sreader = new StreamReader(tcpclient.GetStream(), Encoding.Default);
                sreader.ReadLine();
                strRet = Logon(tcpclient, user, pass);   //登入遠端主機
                if (JudgeString(strRet) != "+OK")
                {
                    MessageBox.Show("使用者名稱或密碼不匹配");
                    return;
                }
                arrRet = StaticMailBox(tcpclient);       //獲取遠端主機中指定使用者的郵件資訊
                if (arrRet[0] != "+OK")
                {
                    MessageBox.Show("出錯了!");
                    return;
                }
                richTextBox1.AppendText("當前使用者:" + user + "\n");
                richTextBox1.AppendText("郵箱中共有:" + arrRet[1] + "封郵件" + "\n");
                richTextBox1.AppendText("共佔:" + arrRet[2] + "Byte");
                k = Convert.ToInt32(arrRet[1]);
                txtPOP.ReadOnly = txtMail.ReadOnly = txtPwd.ReadOnly = true;
                btnLogin.Enabled = false;
                btnReceive.Enabled = true;
                MessageBox.Show("登入成功!");
            }
            catch
            {
                MessageBox.Show("連線伺服器失敗!");
            }
        }
        //“退出”按鈕事件
        private void btnExit_Click(object sender, EventArgs e)
        {
            tcpclient.Close();                          //關閉遠端主機連線
        }
        //“接收”郵件按鈕事件
        private void btnReceive_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtNum.Text != "")
                {
                    if (Convert.ToInt32(txtNum.Text) > k || Convert.ToInt32(txtNum.Text) <= 0)
                    {
                        MessageBox.Show("輸入的索引錯誤");
                    }
                    else
                    {
                        richTextBox1.Clear();
                        string[] arrRets;
                        //獲得遠端主機上指定郵件的相關資訊,儲存到一個string型別的陣列中
                        arrRets = PopMail(tcpclient, Convert.ToInt32(txtNum.Text));
                        richTextBox1.AppendText("當前是第" + txtNum.Text + "封信" + "\n");
                        richTextBox1.AppendText("郵件日期:" + arrRets[1] + "\n");
                        richTextBox1.AppendText("發信人:" + arrRets[2] + "\n");
                        richTextBox1.AppendText("收信人:" + arrRets[3] + "\n");
                        richTextBox1.AppendText("郵件主題:" + Base64Decode(arrRets[4]) + "\n");
                        richTextBox1.AppendText("郵件內容:" + Base64Decode(arrRets[5]));
                    }
                }
                else
                {
                    MessageBox.Show("郵件索引錯誤");
                }
            }
            catch
            {
            }
        }

        private void txtPwd_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
                btnLogin.Focus();
        }

        private void txtPOP_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
                txtMail.Focus();
        }

        private void txtMail_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
                txtPwd.Focus();
        }

        private void txtNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
                btnReceive.Focus();
        }

        private void frmReceive_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                tcpclient.Close();
            }
            catch { }
        }
    }
}