ASP.NET2.0寄送電子郵件範例程式碼

來源:互聯網
上載者:User

一個國外的英文網站上有非常詳細的代碼說明:

相關的資料地址:http://www.systemnetmail.com/

 

下面的代碼是我參考資料寫出的一個樣本:

 

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<br>" + e.ToString(); //發送失敗,返回fail
            }
            return "ok"; //發送成功,返回 ok

        }
    }
}


 

web.config的內容如下:

 

<system.net>
    <mailSettings>
      <!-- 發送郵件設定,把這裡的郵箱地址和密碼設定成你自己的就ok了 -->
      <smtp from="yours@126.com">
        <network host="smtp.126.com" port="25" userName="yours@126.com" password="123456" defaultCredentials="false"/>
      </smtp>
    </mailSettings>
  </system.net>


 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.