EmbeddedMailObject Construtores

Definição

Inicializa uma nova instância da classe EmbeddedMailObject.

Sobrecargas

EmbeddedMailObject()

Inicializa uma nova instância da classe EmbeddedMailObject.

EmbeddedMailObject(String, String)

Inicializa uma nova instância da classe EmbeddedMailObject, usando o caminho e o nome do identificador especificados para popular o objeto.

EmbeddedMailObject()

Inicializa uma nova instância da classe EmbeddedMailObject.

public:
 EmbeddedMailObject();
public EmbeddedMailObject ();
Public Sub New ()

Comentários

Para obter ou definir o identificador do item inserido, use a Name propriedade . Para obter ou definir o caminho para o item inserido, use a Path propriedade . Ambas as propriedades devem ser definidas para inserir com êxito o item na mensagem de email.

Confira também

Aplica-se a

EmbeddedMailObject(String, String)

Inicializa uma nova instância da classe EmbeddedMailObject, usando o caminho e o nome do identificador especificados para popular o objeto.

public:
 EmbeddedMailObject(System::String ^ name, System::String ^ path);
public EmbeddedMailObject (string name, string path);
new System.Web.UI.WebControls.EmbeddedMailObject : string * string -> System.Web.UI.WebControls.EmbeddedMailObject
Public Sub New (name As String, path As String)

Parâmetros

name
String

O nome usado como o identificador do item a ser inserido na mensagem de email. Para obter mais informações, consulte Name.

path
String

O caminho usado para recuperar um item a ser inserido na mensagem de email. Para obter mais informações, consulte Path.

Exemplos

O exemplo de código a seguir mostra um exemplo de code-behind de uma página ASP.NET que usa um ChangePassword controle e inclui um manipulador de eventos para o SendingMail evento chamado SendingMail. Este exemplo de código pressupõe que o site ASP.NET foi configurado para usar a associação ASP.NET e a autenticação do Forms e que um usuário foi criado cujo nome e senha são conhecidos por você. Para obter mais informações, consulte Como implementar a autenticação de formulários simples.

Se a alteração de senha for bem-sucedida, o código no SendingMail manipulador de eventos tentará enviar uma mensagem de email ao usuário para confirmar a alteração. O SMTP já deve estar configurado no servidor para que este exemplo de código funcione. Para obter informações sobre como configurar um servidor SMTP, consulte Como instalar e configurar servidores virtuais SMTP no IIS 6.0. Para 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.

Se um servidor de email não estiver configurado corretamente ou ocorrer algum outro erro e a mensagem de email não puder ser enviada, a SendMailError função será chamada. Uma mensagem é exibida para o usuário. Além disso, um evento é registrado no log de eventos do Aplicativo Windows com a suposição de que uma fonte de evento chamada MySamplesSite já existe. Consulte o exemplo de código abaixo para criar a origem do evento especificada. Para obter mais informações sobre como criar uma origem de evento, consulte Tratamento de eventos do servidor em páginas de ASP.NET Web Forms. A Handled propriedade do SendMailErrorEventArgs objeto é definida como true para indicar que o erro foi tratado.

O exemplo de código a seguir demonstra o uso de uma página .aspx.

<%@ Page Language="C#" CodeFile="ChangePassword.cs" Inherits="ChangePassword_cs_aspx" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
  <title>ChangePassword using code-behind 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"
      ContinueDestinationPageUrl="~/Default.aspx" >
    </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" CodeFile="ChangePassword.vb" Inherits="ChangePassword_vb_aspx" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>ChangePassword using code-behind 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"
      ContinueDestinationPageUrl="~/Default.aspx"
      OnSendingMail="_SendingMail" 
      OnSendMailError="_SendMailError" >
    </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>

O exemplo de código a seguir demonstra o uso de um arquivo code-behind.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class ChangePassword_cs_aspx : System.Web.UI.Page
{
    protected void Page_Load(Object sender, EventArgs e)
    {
        // Manually register the event-handling methods.
        ChangePassword1.SendingMail += new MailMessageEventHandler(this._SendingMail);
        ChangePassword1.SendMailError += new SendMailErrorEventHandler(this._SendMailError);

        ChangePassword1.MailDefinition.BodyFileName = "~/Attachments/ChangePasswordMail.htm";

        EmbeddedMailObject loginGif = new EmbeddedMailObject();
        loginGif.Name = "LoginGif";
        loginGif.Path = "~/Attachments/Login.gif";

        EmbeddedMailObject privacyNoticeTxt = new EmbeddedMailObject();
        privacyNoticeTxt.Name = "PrivacyNoticeTxt";
        privacyNoticeTxt.Path = "~/Attachments/PrivacyNotice.txt";

        ChangePassword1.MailDefinition.EmbeddedObjects.Add(loginGif);
        ChangePassword1.MailDefinition.EmbeddedObjects.Add(privacyNoticeTxt);
    }

    protected void _SendingMail(object sender, MailMessageEventArgs e)
    {
        Message1.Visible = true;
        Message1.Text = "Sent mail to you to confirm the password change.";

        System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress("someone@example.com", "Someone");
        System.Net.Mail.MailAddress copy = new System.Net.Mail.MailAddress("someone@example.com", "Someone");

        e.Message.From = from;
        e.Message.CC.Add(copy);
        e.Message.Subject = "Activity information for you";
        e.Message.IsBodyHtml = true;
    }

    protected void _SendMailError(object sender, SendMailErrorEventArgs e)
    {
        Message1.Visible = true;
        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.Source = "MySamplesSite";
        myLog.Log = "Application";
        myLog.WriteEntry(
          "Sending mail via SMTP failed with the following error: " +
          e.Exception.Message.ToString(),
          System.Diagnostics.EventLogEntryType.Error);

        e.Handled = true;
    }
}
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls

Partial Class ChangePassword_vb_aspx
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal Sender As Object, ByVal e As System.EventArgs)
        AddHandler ChangePassword1.SendingMail, AddressOf Me._SendingMail
        AddHandler ChangePassword1.SendMailError, AddressOf Me._SendMailError
        ChangePassword1.MailDefinition.BodyFileName = "~/Attachments/ChangePasswordMail.htm"
        ChangePassword1.MailDefinition.Cc = "someone@example.com"
        ChangePassword1.MailDefinition.From = "someone@example.com"

        Dim loginGif As New EmbeddedMailObject
        loginGif.Name = "LoginGif"
        loginGif.Path = "~/Attachments/Login.gif"

        Dim privacyNoticeTxt As New EmbeddedMailObject
        privacyNoticeTxt.Name = "PrivacyNoticeTxt"
        privacyNoticeTxt.Path = "~/Attachments/PrivacyNotice.txt"

        ChangePassword1.MailDefinition.EmbeddedObjects.Add(loginGif)
        ChangePassword1.MailDefinition.EmbeddedObjects.Add(privacyNoticeTxt)
    End Sub

    Protected Sub _SendingMail(ByVal Sender As Object, ByVal e As MailMessageEventArgs)
        Message1.Visible = True
        Message1.Text = "Sent mail to you to confirm the password change."

        e.Message.Subject = "Activity information for you"
        e.Message.IsBodyHtml = True

    End Sub

    Protected Sub _SendMailError(ByVal Sender As Object, ByVal e As SendMailErrorEventArgs)
        Message1.Visible = True
        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

End Class

Use o exemplo de código a seguir se precisar adicionar programaticamente a fonte de eventos chamada MySamplesSite ao log do aplicativo. Essa fonte de evento deve existir para que o primeiro exemplo de código funcione corretamente. O exemplo de código a seguir requer privilégios de administrador.

#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 ChangePasswordMail.htm para o código de exemplo anterior.

Importante

O envio de nomes de conta de usuário ou senhas em uma mensagem de email é uma possível ameaça à segurança. Email mensagens normalmente são enviadas em texto sem formatação e podem ser lidas por aplicativos especiais de "detecção" de rede. Para melhorar a segurança, use as mitigações descritas em Protegendo controles de logon.

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

Confira também

Aplica-se a