SendMailErrorEventArgs.Exception Właściwość

Definicja

Zwraca wyjątek zgłaszany przez usługę poczty SMTP, gdy nie można wysłać wiadomości e-mail.

public:
 property Exception ^ Exception { Exception ^ get(); void set(Exception ^ value); };
public Exception Exception { get; set; }
member this.Exception : Exception with get, set
Public Property Exception As Exception

Wartość właściwości

Exception Obiekt, który zawiera wyjątek.

Przykłady

Poniższy przykład kodu przedstawia stronę ASP.NET, która używa ChangePassword kontrolki sieci Web i zawiera procedurę obsługi zdarzeń dla SendMailError zdarzenia o nazwie SendMailError. W przykładzie kodu przyjęto założenie, że witryna sieci Web ASP.NET została skonfigurowana do używania ASP.NET członkostwa i uwierzytelniania formularzy oraz że użytkownik został utworzony, którego nazwa i hasło są dla Ciebie znane. Aby uzyskać więcej informacji, zobacz How to: Implement Simple Forms Authentication (Instrukcje: implementowanie uwierzytelniania za pomocą prostych formularzy).

Jeśli zmiana hasła powiedzie się, kod w SendingMail programie obsługi zdarzeń próbuje wysłać wiadomość e-mail do użytkownika w celu potwierdzenia zmiany. Protokół SMTP musi być już skonfigurowany na serwerze, aby ten przykład kodu działał. Aby uzyskać informacje o sposobie konfigurowania serwera SMTP, zobacz How to: Install and Configure SMTP Virtual Servers in IIS 6.0 (Jak zainstalować i skonfigurować serwery wirtualne SMTP w usługach IIS 6.0). Na potrzeby tego przykładu nie jest konieczne skonfigurowanie serwera SMTP; Przykład jest skonstruowany w celu przetestowania błędu wysyłania wiadomości e-mail.

Jeśli serwer poczty nie jest poprawnie skonfigurowany lub wystąpi inny błąd i nie można wysłać wiadomości e-mail, funkcja jest wywoływana SendMailError . Użytkownikowi zostanie wyświetlony komunikat. Ponadto zdarzenie jest rejestrowane w dzienniku zdarzeń aplikacji systemu Windows przy założeniu, że źródło zdarzeń o nazwie MySamplesSite już istnieje. Zobacz poniższy przykład kodu, aby utworzyć określone źródło zdarzeń. Aby uzyskać więcej informacji na temat tworzenia źródła zdarzeń, zobacz Obsługa zdarzeń serwera w ASP.NET Web Forms Pages. Właściwość HandledSendMailErrorEventArgs obiektu jest ustawiona na , aby wskazać true , że błąd został obsłużony.

<%@ 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>

Użyj poniższego przykładu kodu, jeśli musisz programowo dodać źródło zdarzeń o nazwie MySamplesSite do dziennika aplikacji. To źródło zdarzeń musi istnieć, aby pierwszy przykład kodu działał prawidłowo. Poniższy przykład kodu wymaga uprawnień administratora.

#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

Uwagi

Właściwość Exception zawiera wyjątek zgłaszany przez dostawcę poczty SMTP, gdy nie można wysłać wiadomości e-mail przez kontrolkę ChangePassword lub .CreateUserWizard Najczęstszą przyczyną tego wyjątku jest błąd konfiguracji w <elemecie smtp> (ustawienia sieciowe) pliku konfiguracji maszyny, który generuje następujący komunikat o wyjątku: The transport failed to connect to the server.

Wyjątki nie są zgłaszane w przypadku wystąpienia błędu w wiadomości e-mail podczas osadzania pliku przy użyciu polecenia EmbeddedObjects. Zamiast tego osadzony plik jest wyświetlany jako uszkodzony po wyświetleniu wiadomości e-mail.

Należy ustawić Handled obiekt przekazany jako e parametr SendMailErrorEventArgs, aby true zasygnalizować, że wyjątek został obsłużony. W przeciwnym razie wyjątek zostanie ponownie zgłoszony i zawiera oryginalny stos wywołań i komunikat o błędzie.

Dotyczy

Zobacz też