ChangePassword.SendMailError Evento

Definição

Ocorre quando há um erro de SMTP ao enviar uma mensagem de email para o usuário.Occurs when there is an SMTP error sending an email message to the user.

public:
 event System::Web::UI::WebControls::SendMailErrorEventHandler ^ SendMailError;
public event System.Web.UI.WebControls.SendMailErrorEventHandler SendMailError;
member this.SendMailError : System.Web.UI.WebControls.SendMailErrorEventHandler 
Public Custom Event SendMailError As SendMailErrorEventHandler 

Tipo de evento

SendMailErrorEventHandler

Exemplos

O exemplo de código a seguir demonstra uma página ASP.NET que usa um ChangePassword controle da Web e inclui um manipulador de eventos para o SendingMail evento chamado SendingMail .The following code example demonstrates an ASP.NET page that uses a ChangePassword Web control, and includes an event handler for the SendingMail event named SendingMail. O exemplo de código pressupõe que o site ASP.NET foi configurado para usar associação e autenticação de formulários do ASP.NET, e que um usuário foi criado cujo nome e senha são conhecidos por você.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. Para obter mais informações, consulte como implementar a autenticação de formulários simples.For more information, see How to: Implement Simple Forms Authentication.

Se a alteração de senha for realizada com sucesso, o código tentará usar o SMTP para enviar uma mensagem de email ao usuário para confirmar a alteração.If the password change succeeds, the code attempts to use SMTP to send an email message to the user to confirm the change. Isso é feito no SendingMail manipulador de eventos.This is done in theSendingMail event handler. Para obter informações sobre como configurar um servidor SMTP, consulte como instalar e configurar servidores virtuais SMTP no IIS 6,0.For information about how to configure an SMTP server, see How to: Install and Configure SMTP Virtual Servers in IIS 6.0. Para os fins deste exemplo, não é necessário configurar um servidor SMTP; o exemplo é construído para testar uma falha ao enviar uma mensagem de email.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.

Se um servidor de email não estiver configurado corretamente ou algum outro erro ocorrer e a mensagem de email não puder ser enviada, a SendMailError função será chamada.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. Uma mensagem é exibida para o usuário.A message is displayed to the user. Além disso, um evento é registrado no log de eventos de aplicativo do Windows com a suposição de que uma fonte de evento chamada MySamplesSite já exista.In addition, an event is logged to the Windows Application event log with the assumption that an event source named MySamplesSite already exists. Consulte o exemplo de código abaixo para criar a origem do evento especificado.See the code example below to create the specified event source. Para obter mais informações sobre como criar uma origem do evento, consulte manipulação de eventos do servidor em ASP.NET Web Forms páginas.For more information about creating an event source, see Server Event Handling in ASP.NET Web Forms Pages. A Handled Propriedade do SendMailErrorEventArgs objeto é definida como true para indicar que o erro foi tratado.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>

Use o exemplo de código a seguir se você precisar adicionar programaticamente a origem do evento chamada MySamplesSite ao seu log de aplicativo.Use the following code example if you need to programmatically add the event source named MySamplesSite to your Application log. Essa origem do evento deve existir para que o primeiro exemplo de código funcione corretamente.This event source must exist in order for the first code example to work correctly. O exemplo de código a seguir requer privilégios de administrador.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

O código de exemplo a seguir pode ser usado como o arquivo de ChangePasswordMail.htm para o código de exemplo anterior.The following example code can be used as the ChangePasswordMail.htm file for the previous example code.

Importante

O envio de nomes de conta de usuário ou senhas no email é uma ameaça potencial à segurança.Sending user account names or passwords in email is a potential security threat. As mensagens de email são normalmente enviadas em texto sem formatação e podem ser lidas por aplicativos especiais de "detecção" de rede.Email messages are typically sent in plain text and can be read by special network "sniffing" applications. Para melhorar a segurança, use as atenuações descritas em protegendo controles de logon.To improve security, use the mitigations that are described in Securing Login Controls.

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

Comentários

O SendMailError evento é gerado quando o provedor de email SMTP gera uma exceção ao tentar enviar uma mensagem de email depois que os usuários tiverem alterado sua senha.The SendMailError event is raised when the SMTP mail provider throws an exception when trying to send an email message after users have changed their password. O motivo mais comum para esse evento é que a smtp seção do arquivo de Web.config está incorreta.The most common reason that this event is raised is that the smtp section of the Web.config file is incorrect. Para obter mais informações sobre a smtp seção, consulte <smtp> elemento (configurações de rede).For more information about the smtp section, see <smtp> Element (Network Settings).

O manipulador de eventos padrão não SendMailError captura nem manipula o erro SMTP do sistema de email.The default SendMailError event handler does not catch or handle the SMTP error from the mail system. Seu SendMailError manipulador de eventos deve definir a Handled Propriedade do SendMailErrorEventArgs objeto como para true impedir que o erro seja exibido aos usuários.Your SendMailError event handler must set the Handled property of the SendMailErrorEventArgs object to true in order to stop the error from being displayed to users.

Para obter mais informações sobre como manipular eventos, consulte manipulando e gerando eventos.For more information about handling events, see Handling and Raising Events.

Aplica-se a

Confira também