Share via


ChangePassword.OnSendingMail(MailMessageEventArgs) 方法

定義

在電子郵件訊息傳送到 SMTP 伺服器以進行處理之前,引發 SendingMail 事件。 然後 SMTP 伺服器會將電子郵件訊息傳送給使用者。

protected:
 virtual void OnSendingMail(System::Web::UI::WebControls::MailMessageEventArgs ^ e);
protected virtual void OnSendingMail (System.Web.UI.WebControls.MailMessageEventArgs e);
abstract member OnSendingMail : System.Web.UI.WebControls.MailMessageEventArgs -> unit
override this.OnSendingMail : System.Web.UI.WebControls.MailMessageEventArgs -> unit
Protected Overridable Sub OnSendingMail (e As MailMessageEventArgs)

參數

e
MailMessageEventArgs

包含事件資料的 MailMessageEventArgs 物件。

範例

下列程式碼範例示範使用 ChangePassword Web 控制項的 ASP.NET 網頁,並包含名為 SendingMailSendingMail 事件的事件處理常式。 程式碼範例假設 ASP.NET 網站已設定為使用 ASP.NET 成員資格和表單驗證,而且已建立使用者的名稱和密碼已知。 如需詳細資訊,請參閱 如何:實作簡單表單驗證

如果密碼變更成功,程式碼會嘗試使用 SMTP 將電子郵件訊息傳送給使用者以確認變更。 這會在事件處理常式中 SendingMail 完成。 如需如何設定 SMTP 伺服器的資訊,請參閱 如何:在 IIS 6.0 中安裝和設定 SMTP 虛擬伺服器。 針對此範例的目的,不需要設定 SMTP 伺服器;此範例是建構來測試傳送電子郵件訊息失敗。

如果未正確設定郵件伺服器,或發生其他錯誤,且無法傳送電子郵件訊息,則會呼叫 函 SendMailError 式。 系統會向使用者顯示訊息。 此外,事件會記錄到 Windows 應用程式事件記錄檔,並假設名為 MySamplesSite 的事件來源已經存在。 請參閱下列程式碼範例,以建立指定的事件來源。 如需建立事件來源的詳細資訊,請參閱ASP.NET Web Forms Pages 中的伺服器事件處理。 物件的 Handled 屬性 SendMailErrorEventArgs 設定 true 為 ,表示已處理錯誤。

<%@ Page Language="C#" AutoEventWireup="True" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  void MySendingMail(object sender, MailMessageEventArgs e)
  {
    Message1.Text = "Sent mail to you to confirm the password change.";
  }

  void MySendMailError(object sender, SendMailErrorEventArgs e)
  {
    Message1.Text = "Could not send email to confirm password change.";

    // The MySamplesSite event source has already been created by an administrator.
    System.Diagnostics.EventLog myLog = new System.Diagnostics.EventLog();
    myLog.Log = "Application";
    myLog.Source = "MySamplesSite";
    myLog.WriteEntry(
        "Sending mail via SMTP failed with the following error: " + 
        e.Exception.Message.ToString(), 
        System.Diagnostics.EventLogEntryType.Error);

    e.Handled = true;
  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>ChangePassword including a SendMailError Event</title>
</head>
<body>
  <form id="form1" runat="server">
  <div style="text-align:center">

    <h1>ChangePassword</h1>
    
    <asp:LoginView ID="LoginView1" Runat="server" 
      Visible="true">
      <LoggedInTemplate>
        <asp:LoginName ID="LoginName1" Runat="server" FormatString="You are logged in as {0}." />
        <br />
      </LoggedInTemplate>
      <AnonymousTemplate>
        You are not logged in
      </AnonymousTemplate>
    </asp:LoginView><br />
    
    <asp:ChangePassword ID="ChangePassword1" Runat="server"
      BorderStyle="Solid" 
      BorderWidth="1" 
      CancelDestinationPageUrl="~/Default.aspx" 
      DisplayUserName="true"
      OnSendingMail="MySendingMail" 
      OnSendMailError="MySendMailError" 
      ContinueDestinationPageUrl="~/Default.aspx" >
      <MailDefinition 
        BodyFileName="~\MailFiles\ChangePasswordMail.htm" 
        Subject="Activity information for you">
        <EmbeddedObjects>
          <asp:EmbeddedMailObject Name="LoginGif" Path="~\MailFiles\Login.gif" />
          <asp:EmbeddedMailObject Name="PrivacyNoticeTxt" Path="~\MailFiles\PrivacyNotice.txt" />
        </EmbeddedObjects>
      </MailDefinition>
    </asp:ChangePassword><br />
  
    <asp:Label ID="Message1" Runat="server" ForeColor="Red" /><br />

    <asp:HyperLink ID="HyperLink1" Runat="server" 
      NavigateUrl="~/Default.aspx">
      Home
    </asp:HyperLink>
    
  </div>
  </form>
</body>
</html>
<%@ Page Language="VB" AutoEventWireup="True" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  Public Sub MySendingMail(ByVal Sender As Object, ByVal e As MailMessageEventArgs)
    Message1.Text = "Sent mail to you to confirm the password change."
  End Sub

  Public Sub MySendMailError(ByVal Sender As Object, ByVal e As SendMailErrorEventArgs)
    Message1.Text = "Could not send mail to confirm the password change."
    
    ' The MySamplesSite event source has already been created by an administrator.
    Dim myLog As System.Diagnostics.EventLog
    myLog = new System.Diagnostics.EventLog
    myLog.Log = "Application"
    myLog.Source = "MySamplesSite"
    myLog.WriteEntry("Sending mail via SMTP failed with the following error: " & e.Exception.Message.ToString(), System.Diagnostics.EventLogEntryType.Error)

    e.Handled = True
    
  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>ChangePassword including a SendMailError Event</title>
</head>
<body>
  <form id="form1" runat="server">
  <div style="text-align:center">

    <h1>ChangePassword</h1>
    
    <asp:LoginView ID="LoginView1" Runat="server" 
      Visible="true">
      <LoggedInTemplate>
        <asp:LoginName ID="LoginName1" Runat="server" FormatString="You are logged in as {0}." />
        <br />
      </LoggedInTemplate>
      <AnonymousTemplate>
        You are not logged in
      </AnonymousTemplate>
    </asp:LoginView><br />
    
    <asp:ChangePassword ID="ChangePassword1" Runat="server"
      BorderStyle="Solid" 
      BorderWidth="1" 
      CancelDestinationPageUrl="~/Default.aspx" 
      DisplayUserName="true"
      OnSendingMail="MySendingMail" 
      OnSendMailError="MySendMailError" 
      ContinueDestinationPageUrl="~/Default.aspx" >
      <MailDefinition 
        BodyFileName="~\MailFiles\ChangePasswordMail.htm" 
        Subject="Activity information for you">
        <EmbeddedObjects>
          <asp:EmbeddedMailObject Name="LoginGif" Path="~\MailFiles\Login.gif" />
          <asp:EmbeddedMailObject Name="PrivacyNoticeTxt" Path="~\MailFiles\PrivacyNotice.txt" />
        </EmbeddedObjects>
      </MailDefinition>
    </asp:ChangePassword><br />
  
    <asp:Label ID="Message1" Runat="server" ForeColor="Red" /><br />

    <asp:HyperLink ID="HyperLink1" Runat="server" 
      NavigateUrl="~/Default.aspx">
      Home
    </asp:HyperLink>
    
  </div>
  </form>
</body>
</html>

如果您需要以程式設計方式將名為 MySamplesSite 的事件來源新增至應用程式記錄檔,請使用下列程式碼範例。 此事件來源必須存在,第一個程式碼範例才能正常運作。 下列程式碼範例需要系統管理員許可權。

#region Using directives

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

#endregion

namespace CreateEventSource
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
                // Create the source, if it does not already exist.
                if (!EventLog.SourceExists("MySamplesSite"))
                {
                    EventLog.CreateEventSource("MySamplesSite", "Application");
                    Console.WriteLine("Creating Event Source");
                }

                // Create an EventLog instance and assign its source.
                EventLog myLog = new EventLog();
                myLog.Source = "MySamplesSite";

                // Write an informational entry to the event log.    
                myLog.WriteEntry("Testing writing to event log.");

                Console.WriteLine("Message written to event log.");
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception:");
                Console.WriteLine("{0}", e.ToString());
            }
        }
    }
}
Imports System.Collections.Generic
Imports System.Text
Imports System.Diagnostics


Namespace CreateEventSource
  Class Program
    Sub Main()

        Try
            ' Create the source, if it does not already exist.
            If Not (EventLog.SourceExists("MySamplesSite")) Then
                EventLog.CreateEventSource("MySamplesSite", "Application")
                Console.WriteLine("Creating Event Source")
            End If

            ' Create an EventLog instance and assign its source.
            Dim myLog As New EventLog
            myLog.Source = "MySamplesSite"

            ' Write an informational entry to the event log.
            myLog.WriteEntry("Testing writing to event log.")

            Console.WriteLine("Message written to event log.")
        Catch e As Exception
            Console.WriteLine("Exception:")
            Console.WriteLine(e.ToString)
        End Try

    End Sub
  End Class
End Namespace

下列範例程式碼可用來作為先前範例程式碼的ChangePasswordMail.htm檔案。

重要

在電子郵件中傳送使用者帳戶名稱或密碼是潛在的安全性威脅。 Email訊息通常會以純文字傳送,而且可由特殊網路「探查」應用程式讀取。 若要改善安全性,請使用 保護登入控制項中所述的防護功能。

<html>  
<head><title></title></head>  
<body>  
<form>  

  <h1>Your password for the account named &quot;<%Username%>&quot; has changed.</h1>  

  <p>  
  If you did not initiate this change, please call 1-206-555-0100.  
  </p>  

  <p>  
  <a href="http://www.contoso.com/login.aspx">  
    <img src="cid:LoginGif" alt="Log In" />  
  </a>   
  </p>  

  <p>  
  Please read our attached Privacy Notice.  
  </p>  

</form>  
</body>  
</html>  

備註

OnSendingMail使用 方法來修改在使用者變更密碼之後傳送給使用者的電子郵件訊息。 物件的 Message 屬性 MailMessageEventArgs 會傳送至 SMTP 伺服器進行處理。 修改 物件的屬性 MailMessage ,以修改電子郵件訊息。

只有在屬性所指定的 MailDefinition 物件屬性 MailDefinition 指向有效的檔案名時 BodyFileName ,才會建立Email訊息。

重要

在電子郵件中傳送使用者帳戶名稱或密碼是潛在的安全性威脅。 Email訊息通常會以純文字傳送,而且可由特殊網路「探查」應用程式讀取。 若要改善安全性,請使用 保護登入控制項中所述的防護功能。

引發事件會透過委派叫用此事件處理常式。 如需詳細資訊,請參閱ASP.NET Web Forms 頁面中的伺服器事件處理

OnSendingMail 方法也允許衍生類別處理事件,而不用附加委派。 這是在衍生類別中處理事件的慣用技巧。

給繼承者的注意事項

在衍生類別中覆 OnSendingMail(MailMessageEventArgs) 寫 方法時,請務必呼叫 OnSendingMail(MailMessageEventArgs) 基類的 方法,讓已註冊的委派接收事件。

適用於

另請參閱