SendMailErrorEventHandler 代理人

定義

表示方法,此方法可處理例如 ChangePasswordCreateUserWizardPasswordRecovery 等控制項的 SendMailError 事件。Represents the method that handles the SendMailError event of controls such as the ChangePassword control, the CreateUserWizard control, and the PasswordRecovery control.

public delegate void SendMailErrorEventHandler(System::Object ^ sender, SendMailErrorEventArgs ^ e);
public delegate void SendMailErrorEventHandler(object sender, SendMailErrorEventArgs e);
type SendMailErrorEventHandler = delegate of obj * SendMailErrorEventArgs -> unit
Public Delegate Sub SendMailErrorEventHandler(sender As Object, e As SendMailErrorEventArgs)

參數

sender
Object

事件的來源。The source of the event.

e
SendMailErrorEventArgs

包含事件資料的 SendMailErrorEventArgs 物件。A SendMailErrorEventArgs object that contains the event data.

繼承
SendMailErrorEventHandler

範例

下列程式碼範例示範使用 Web 控制項的 ASP.NET 網頁 ChangePassword ,並包含名為之事件的事件處理常式 SendMailError SendMailErrorThe following code example demonstrates an ASP.NET page that uses a ChangePassword Web control, and includes an event handler for the SendMailError event named SendMailError. 此程式碼範例假設 ASP.NET 網站已設定為使用 ASP.NET 成員資格和表單驗證,而且已建立使用者知道您的名稱和密碼。The code example assumes that the ASP.NET Web site has been configured to use ASP.NET membership and Forms authentication, and that a user has been created whose name and password are known to you. 如需詳細資訊,請參閱如何:執行簡單的表單驗證For more information, see How to: Implement Simple Forms Authentication.

如果密碼變更成功,則程式碼會嘗試使用 SMTP 將電子郵件訊息傳送給使用者,以確認變更。If the password change succeeds, the code attempts to use SMTP to send an email message to the user to confirm the change. 這會在 SendingMail 事件處理常式中完成。This is done in the SendingMail event handler. 如需有關如何設定 SMTP 伺服器的詳細資訊,請參閱如何:在 IIS 6.0 中安裝和設定 Smtp 虛擬伺服器For information about how to configure an SMTP server, see How to: Install and Configure SMTP Virtual Servers in IIS 6.0. 基於此範例的目的,不需要設定 SMTP 伺服器。此範例的結構是為了測試傳送電子郵件訊息的失敗。For the purposes of this example, it is not necessary to configure an SMTP server; the example is constructed to test for a failure to send an email message.

如果郵件伺服器未正確設定,或發生其他錯誤,而且無法傳送電子郵件訊息,則 SendMailError 會呼叫函式。If a mail server is not configured correctly or some other error occurs and the email message cannot be sent, the SendMailError function is called. 使用者會看到一則訊息。A message is displayed to the user. 此外,系統會將事件記錄到 Windows 應用程式事件記錄檔中,假設名為 MySamplesSite 的事件來源已經存在。In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. 請參閱下面的程式碼範例,以建立指定的事件來源。See the code example below to create the specified event source. 如需建立事件來源的詳細資訊,請參閱ASP.NET Web Forms 頁面中的伺服器事件處理For more information about creating an event source, see Server Event Handling in ASP.NET Web Forms Pages. Handled物件的屬性 SendMailErrorEventArgs 會設定為 true ,表示已處理錯誤。The Handled property of the SendMailErrorEventArgs object is set to true to indicate that the error has been handled.

<%@ 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 的事件來源新增至您的應用程式記錄檔,請使用下列程式碼範例。Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. 必須要有此事件來源,第一個程式碼範例才能正常運作。This event source must exist in order for the first code example to work correctly. 下列程式碼範例需要系統管理員許可權。The following code example requires Administrator privileges.

#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

備註

建立 SendMailErrorEventHandler 委派時,必須識別處理事件的方法。When you create a SendMailErrorEventHandler delegate, you identify the method that will handle the event. 若要將事件與事件處理常式產生關聯,請將委派的實例加入至事件。To associate the event with the event handler, add an instance of the delegate to the event. 事件處理常式會在每次發生事件時呼叫,除非您將委派從事件中移除。The event handler is called whenever the event occurs, unless you remove the delegate from the event. 如需事件處理常式委派的詳細資訊,請參閱ASP.NET Web Forms 頁面中的伺服器事件處理For more information about event-handler delegates, see Server Event Handling in ASP.NET Web Forms Pages.

處理 SendMailError 事件可讓您的 Web 應用程式繼續執行,即使在嘗試傳送電子郵件訊息時,也會發生例外狀況。Handling the SendMailError event allows your Web application to continue running, even if an exception occurs when trying to send an email message. 例如,如果在使用者透過多步驟的 wizard 進行工作時發生例外狀況,這就很有用。For example, this is useful if the exception occurs when a user is working through a multi-step wizard. 最好是記錄錯誤、向使用者顯示資訊訊息,並允許使用者完成嚮導,而不是終止應用程式。It is preferable to log the error, display an informative message to the user, and allow the user to complete the wizard rather than terminate the application.

如果您未建立事件的事件處理常式 SendMailError ,或建立事件處理常式但將 Handled 屬性設定為,則如果在傳送 false 電子郵件訊息時發生錯誤,則 Web 應用程式將會停止執行,而且 ASP.NET 會顯示錯誤訊息。If you do not create an event handler for the SendMailError event, or if you create an event handler but leave the Handled property set to false, your Web application will stop running if an error occurs when sending an email message, and ASP.NET will display an error message.

OnSendMailError方法也允許衍生類別處理事件,而不是 SendMailErrorEventHandlerThe OnSendMailError method also allows derived classes to handle the event instead of the SendMailErrorEventHandler. 這是在衍生自或的類別中處理事件的慣用技巧 ChangePassword CreateUserWizardThis is the preferred technique for handling the event in a class that is derived from ChangePassword or CreateUserWizard.

如需處理事件的詳細資訊,請參閱ASP.NET Web Forms 頁面中的伺服器事件處理For more information about handling events, see Server Event Handling in ASP.NET Web Forms Pages.

擴充方法

GetMethodInfo(Delegate)

取得表示特定委派所代表之方法的物件。Gets an object that represents the method represented by the specified delegate.

適用於

另請參閱