ASP.NET2.0傳送電子郵件示例程式碼

iDotNetSpace發表於2009-01-12

下面的程式碼是我參考資料寫出的一個示例:

 

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Mail;

namespace Email_Test.aspx
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string emailTitle = "測試email";
            string toEmail = "seagreen7@yeah.net";
            string mycontent = "這是測試郵件內容";
            string myResult = SendHtmlEmail(emailTitle, toEmail, mycontent);
            if (myResult == "ok")
            { this.Label1.Text = "恭喜,郵件已經成功傳送給" + toEmail; }
            else
            { this.Label1.Text = "抱歉,郵件傳送失敗,請檢查web.config檔案的配置資訊 system.net 節點。" ; }
        }
        public static string SendHtmlEmail(string EmailTitle, string destEmail, string EmailContent)
        {
            try
            {
                // 讀取web.config中的郵件傳送的配置資訊
                //在這裡的程式碼中,我們不需要設定SmtpClient類的任何屬性,因為它們已經在Web.config檔案中指定了

                //create the mail message
                MailMessage mail = new MailMessage();

                //set the addresses
                mail.To.Add(destEmail);

                //set the content
                mail.Subject = EmailTitle;

                //screen scrape the html
                string html = EmailContent;
                mail.Body = html;
                mail.IsBodyHtml = true;

                //send the message
                SmtpClient smtp = new SmtpClient();
                smtp.Send(mail);
            }
            catch (Exception e)
            {
                return "fail
" + e.ToString(); //傳送失敗,返回fail
            }
            return "ok"; //傳送成功,返回 ok

        }
    }
}

 

 

web.config的內容如下:

 


   
      <!-- 傳送郵件設定,把這裡的郵箱地址和密碼設定成你自己的就ok了 --&gt
      yours@126.com">
        yours@126.com" password="123456" defaultCredentials="false"/>
     

   

 


 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-536503/,如需轉載,請註明出處,否則將追究法律責任。

相關文章