C#實現收發郵件功能

一、服務端

    TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 13000);//定義監聽器
    server.Start();//啟動監聽器
    byte[] buffer = new byte[1024]; //創建一個容器用於接受數據
    string data = null;
    while (true)
    {
        //等待客戶端連接過來
        TcpClient client = server.AcceptTcpClient();

        //Task<TcpClient> task1 = server.AcceptTcpClientAsync();
        //Socket socket = server.AcceptSocket();
        //Task<Socket> task2 = server.AcceptSocketAsync();
        //server.Pending();

        //取得客戶端發送過來的數據 
        int len = client.Available;//獲取已經從網絡流接收且可供讀取的數據量
        NetworkStream nstream = client.GetStream(); //返回一個可供讀寫的網絡流
        int bytesRead;
        do
        {
            bytesRead = nstream.Read(buffer, 0, buffer.Length); //接收消息
            data = Encoding.UTF8.GetString(buffer, 0, bytesRead); //先將接收到的數據轉化可輸出的字符串類型
            Console.WriteLine("收到消息:" + data); 輸出收到的信息
            byte[] msg = Encoding.UTF8.GetBytes(data.ToUpper());
            nstream.Write(buffer, 0, buffer.Length);//發送消息
        } while (bytesRead > 0);
        nstream.Close(); //1.先釋放流的數據
        client.Close(); //2.再釋放客戶端的連接數據
    }
    server.Stop(); //3.關閉監聽

二、客戶端

    TcpClient client = new TcpClient("127.0.0.1", 13000);//連接服務器
    //或者
    //    TcpClient client=new TcpClient();
    //    client.Connect("127.0.0.1", 13000);
    NetworkStream nstream = client.GetStream();
    //---其他同服務端
    nstream.Close(); //1.先釋放流的數據
    client.Close(); //2.再釋放客戶端的連接數據

三、發送郵件

1、使用MailMessage和SmtpClient發送郵件。

在Wince中,可以使用OpenNetCF.Net.Mail類發送郵件。

    MailMessage mailMessage = new MailMessage
    {
        //發件人
        From = new MailAddress("***@163.com", "您的朋友", Encoding.UTF8),
        Priority = MailPriority.High,
        //郵件主題
        SubjectEncoding = Encoding.UTF8,
        Subject = "Hello",
    };

    //收件人 可以添加多個收件人
    mailMessage.To.Add(new MailAddress("137***[email protected]"));

    //mailMessage.CC 獲取包含此電子郵件的抄送(CC)收件人的地址集合

    //郵件正文            
    mailMessage.IsBodyHtml = true;//如果要發送html格式的消息,需要設置這個屬性
    mailMessage.BodyEncoding = Encoding.UTF8;
    mailMessage.Body = "<p style='color:red;font-size:14px;'>郵件測試</p>";

    //郵件內容即消息正文中中顯示圖片 ,需要為圖片指明src='cid:idname(資源id)'
    AlternateView htmlBody = AlternateView.CreateAlternateViewFromString("<img src='cid:zfp'/>", null, "text/html");
    //然後在LinkedResource加入文件的絕對地址,和ContentType 例如image/gif,text/html...與http請求的響應報文中的ContentType一致
    LinkedResource lr = new LinkedResource("1.gif", "image/gif");
    //綁定上文中指定的idname
    lr.ContentId = "zfp";
    //添加鏈接資源
    htmlBody.LinkedResources.Add(lr);
    mailMessage.AlternateViews.Add(htmlBody);

    //發送附件 指明附件的絕對地址
    Attachment attachment = new Attachment("1.txt");
    mailMessage.Attachments.Add(attachment);

    //創建郵件發送客戶端
    SmtpClient sendClient = new SmtpClient("smtp.qq.com", 25)
    {
        //指定郵箱賬號和密碼
        Credentials = new NetworkCredential(fromMail, "xmxyldrmtvnrddfe")
    };

    //指定如何發送電子郵件
    sendClient.DeliveryMethod = SmtpDeliveryMethod.Network;

    //指定使用使用安全套接字ssl加密的鏈接
    sendClient.EnableSsl = true;
    sendClient.Send(mailMessage);
    //或者可以一步發送
    sendClient.SendAsync(mailMessage, null);

 2、利用TcpClient類收取pop3郵件 

    TcpClient client = new TcpClient("mail.**.com", 443);

    //連接
    NetworkStream ns = client.GetStream();
    StreamReader sr = new StreamReader(ns, Encoding.Default);
    string result = sr.ReadLine(); //返回OK或ER

    //登陸
    StreamWriter sw = new StreamWriter(ns);
    sw.WriteLine("user  b**");
    sw.Flush();
    result = sr.ReadLine();

    sw.WriteLine("pass  **");
    sw.Flush();
    result = sr.ReadLine();
    //獲取郵件數量
    sw.WriteLine("stat");
    sw.Flush();
    result = sr.ReadLine();//result.split(' ')[1]表示郵件數量

    //獲取郵件信息
    sw.WriteLine("top 1 0 ");
    sw.Flush();
    result = sr.ReadLine();
    while (true)
    {
        result = sr.ReadLine();
        if (result == ".") break;
        if (result.Length > 4 && result.Substring(0, 8) == "Subject:")
        {
            //result為標題,亂碼用Base64解碼
            Encoding.GetEncoding("gb2312").GetString(Convert.FromBase64String(result));
        }
    }

到此這篇關於C#實現收發郵件功能的文章就介紹到這瞭。希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: