Condividi tramite


EmbeddedMailObject Costruttori

Definizione

Inizializza una nuova istanza della classe EmbeddedMailObject.

Overload

EmbeddedMailObject()

Inizializza una nuova istanza della classe EmbeddedMailObject.

EmbeddedMailObject(String, String)

Inizializza una nuova istanza della classe EmbeddedMailObject, utilizzando l'identificatore e il percorso specificati per inserire i dati nell'oggetto.

EmbeddedMailObject()

Inizializza una nuova istanza della classe EmbeddedMailObject.

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

Commenti

Per ottenere o impostare l'identificatore dell'elemento incorporato, utilizzare la Name proprietà . Per ottenere o impostare il percorso dell'elemento incorporato, utilizzare la Path proprietà . Entrambe le proprietà devono essere impostate per incorporare correttamente l'elemento nel messaggio di posta elettronica.

Vedi anche

Si applica a

EmbeddedMailObject(String, String)

Inizializza una nuova istanza della classe EmbeddedMailObject, utilizzando l'identificatore e il percorso specificati per inserire i dati nell'oggetto.

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)

Parametri

name
String

Nome utilizzato come identificatore dell'elemento da incorporare nel messaggio di posta. Per altre informazioni, vedere Name.

path
String

Percorso utilizzato per recuperare un elemento da incorporare nel messaggio di posta. Per altre informazioni, vedere Path.

Esempio

Nell'esempio di codice seguente viene illustrato un esempio di code-behind di una pagina di ASP.NET che usa un ChangePassword controllo e include un gestore eventi per l'evento SendingMail denominato SendingMail. In questo esempio di codice si presuppone che il sito Web ASP.NET sia stato configurato per l'uso dell'appartenenza ASP.NET e dell'autenticazione basata su form e che sia stato creato un utente il cui nome e la password sono noti all'utente. Per altre informazioni, vedere Procedura: Implementare l'autenticazione basata su moduli semplici.

Se la modifica della password ha esito positivo, il codice nel SendingMail gestore eventi tenta di inviare un messaggio di posta elettronica all'utente per confermare la modifica. Per consentire il funzionamento di questo esempio di codice, è necessario che SMTP sia già configurato nel server. Per informazioni su come configurare un server SMTP, vedere Procedura: Installare e configurare server virtuali SMTP in IIS 6.0. Ai fini di questo esempio, non è necessario configurare un server SMTP; l'esempio viene costruito per verificare se non è possibile inviare un messaggio di posta elettronica.

Se un server di posta elettronica non è configurato correttamente o si verifica un altro errore e non è possibile inviare il messaggio di posta elettronica, viene chiamata la SendMailError funzione . Viene visualizzato un messaggio all'utente. Inoltre, un evento viene registrato nel registro eventi dell'applicazione Windows presupponendo che esista già un'origine evento denominata MySamplesSite. Vedere l'esempio di codice seguente per creare l'origine evento specificata. Per altre informazioni sulla creazione di un'origine evento, vedere Gestione degli eventi del server in Web Forms ASP.NET Pages. La Handled proprietà dell'oggetto SendMailErrorEventArgs è impostata su true per indicare che l'errore è stato gestito.

Nell'esempio di codice seguente viene illustrato l'uso di una pagina 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>

Nell'esempio di codice seguente viene illustrato l'uso di un file 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

Usare l'esempio di codice seguente se è necessario aggiungere a livello di codice l'origine evento denominata MySamplesSite al registro applicazioni. L'origine evento deve esistere affinché il primo esempio di codice funzioni correttamente. L'esempio di codice seguente richiede privilegi di amministratore.

#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

Il codice di esempio seguente può essere usato come file di ChangePasswordMail.htm per il codice di esempio precedente.

Importante

L'invio di nomi di account utente o password in un messaggio di posta elettronica è una potenziale minaccia per la sicurezza. Email messaggi vengono in genere inviati in testo normale e possono essere letti da applicazioni speciali di "sniffing". Per migliorare la sicurezza, usare le mitigazioni descritte in Protezione dei controlli di accesso.

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

Vedi anche

Si applica a