C# 使用smtp發送郵件


//簡單郵件傳輸協議類
            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
            client.Host = "smtp.163.com";//郵件服務器
            client.Port = 25;//smtp主機上的端口號,默認是25.
            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;//郵件發送方式:經過網絡發送到SMTP服務器
            client.Credentials = new System.Net.NetworkCredential("panthervic", "123456");//憑證,發件人登陸郵箱的用戶名和密碼

            //電子郵件信息類
            System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress("panthervic@163.com", "小明");//發件人Email,在郵箱是這樣顯示的,[發件人:小明<panthervic@163.com>;]
            System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress("43327681@163.com", "小紅");//收件人Email,在郵箱是這樣顯示的, [收件人:小紅<43327681@163.com>;]
            System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(fromAddress, toAddress);//建立一個電子郵件類
            mailMessage.Subject = "郵件的主題";
            string filePath = Server.MapPath("/index.html");//郵件的內容能夠是一個html文本.
            System.IO.StreamReader read = new System.IO.StreamReader(filePath, System.Text.Encoding.GetEncoding("GB2312"));
            string mailBody = read.ReadToEnd();
            read.Close();
            mailMessage.Body = mailBody;//可爲html格式文本
            //mailMessage.Body = "郵件的內容";//可爲html格式文本
            mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;//郵件主題編碼
            mailMessage.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");//郵件內容編碼
            mailMessage.IsBodyHtml = true;//郵件內容是否爲html格式
            mailMessage.Priority = System.Net.Mail.MailPriority.High;//郵件的優先級,有三個值:高(在郵件主題前有一個紅色感嘆號,表示緊急),低(在郵件主題前有一個藍色向下箭頭,表示緩慢),正常(無顯示).
            try
            {
                client.Send(mailMessage);//發送郵件
                //client.SendAsync(mailMessage, "ojb");異步方法發送郵件,不會阻塞線程.
            }
            catch (Exception)
            {
            }
相關文章
相關標籤/搜索