Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
.NET Framework Class Library
MailMessage Class

Represents an e-mail message that can be sent using the SmtpClient class.

System..::.Object
  System.Net.Mail..::.MailMessage

Namespace:  System.Net.Mail
Assembly:  System (in System.dll)
Visual Basic
Public Class MailMessage _
    Implements IDisposable
C#
public class MailMessage : IDisposable
Visual C++
public ref class MailMessage : IDisposable
F#
type MailMessage =  
    class
        interface IDisposable
    end

The MailMessage type exposes the following members.

  NameDescription
Public methodMailMessage()()()Initializes an empty instance of the MailMessage class.
Public methodMailMessage(MailAddress, MailAddress)Initializes a new instance of the MailMessage class by using the specified MailAddress class objects.
Public methodMailMessage(String, String)Initializes a new instance of the MailMessage class by using the specified String class objects.
Public methodMailMessage(String, String, String, String)Initializes a new instance of the MailMessage class.
Top
  NameDescription
Public propertyAlternateViewsGets the attachment collection used to store alternate forms of the message body.
Public propertyAttachmentsGets the attachment collection used to store data attached to this e-mail message.
Public propertyBccGets the address collection that contains the blind carbon copy (BCC) recipients for this e-mail message.
Public propertyBodyGets or sets the message body.
Public propertyBodyEncodingGets or sets the encoding used to encode the message body.
Public propertyCCGets the address collection that contains the carbon copy (CC) recipients for this e-mail message.
Public propertyDeliveryNotificationOptionsGets or sets the delivery notifications for this e-mail message.
Public propertyFromGets or sets the from address for this e-mail message.
Public propertyHeadersGets the e-mail headers that are transmitted with this e-mail message.
Public propertyHeadersEncodingGets or sets the encoding used for the user-defined custom headers for this e-mail message.
Public propertyIsBodyHtmlGets or sets a value indicating whether the mail message body is in Html.
Public propertyPriorityGets or sets the priority of this e-mail message.
Public propertyReplyTo Obsolete. Gets or sets the ReplyTo address for the mail message.
Public propertyReplyToListGets or sets the list of addresses to reply to for the mail message.
Public propertySenderGets or sets the sender's address for this e-mail message.
Public propertySubjectGets or sets the subject line for this e-mail message.
Public propertySubjectEncodingGets or sets the encoding used for the subject content for this e-mail message.
Public propertyToGets the address collection that contains the recipients of this e-mail message.
Top
  NameDescription
Public methodDispose()()()Releases all resources used by the MailMessage.
Protected methodDispose(Boolean)Releases the unmanaged resources used by the MailMessage and optionally releases the managed resources.
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

Instances of the MailMessage class are used to construct e-mail messages that are transmitted to an SMTP server for delivery using the SmtpClient class.

The sender, recipient, subject, and body of an e-mail message may be specified as parameters when a MailMessage is used to initialize a MailMessage object. These parameters may also be set or accessed using properties on the MailMessage object.

The primary mail message headers and elements for the message may be set using the following properties of the MailMessage class.

Mail header or part

Property

Attachments

Attachments

Blind carbon copies (BCC)

Bcc

Carbon copies (CC)

CC

Content-Type

BodyEncoding

Encoding for custom headers

HeadersEncoding

Message body

Body

Priority

Priority

Recipient

To

Reply-To

ReplyToList

Sender

From

Subject

Subject

The MailMessage class also allows an application to access the headers collection for the message using the Headers property. While this collection is read-only (a new collection can not be set), custom headers can be added to or deleted from this collection. Any custom headers added will be included when the MailMessage instance is sent. Before a message is sent, only headers specifically added to this collection in the Headers property are included in the collection. After a the MailMessage instance is sent, the Headers property will also include headers that are set using the associated properties of the MailMessage class or parameters passed when a MailMessage is used to initialize a MailMessage object.

If some mail headers are malformed, they could cause the email message to become corrupted. So any mail header in the headers collection that can be set using a property on the MailMessage class should only be set using the MailMessage class property or as a parameter passed when a MailMessage initializes a MailMessage object. The following list of mail headers should not be added using the Headers property and any values set for these headers using the Headers property will be discarded or overwritten when the message is sent:

  • Bcc

  • Cc

  • Content-ID

  • Content-Location

  • Content-Transfer-Encoding

  • Content-Type

  • Date

  • From

  • Importance

  • MIME-Version

  • Priority

  • Reply-To

  • Sender

  • To

  • X-Priority

If the application does not specify an X-Sender header using the Headers property, the MailMessage class will create one when the message is sent.

Use the AlternateViews property to specify copies of an e-mail message in different formats. For example, if you send a message in HTML, you might also want to provide a plain text version in case some of the recipients use e-mail readers that cannot display HTML content. For an example that demonstrates creating a message with alternate views, see AlternateViews.

Use the Attachments property to add attachments to an e-mail message. For an example that demonstrates creating a message with an attachment, see Attachments.

After assembling your e-mail message, you can send it by using the Send or SendAsync methods.

The following code example demonstrates creating and sending an e-mail message that includes an attachment.

C#
        public static void CreateMessageWithAttachment(string server)
        {
            // Specify the file to be attached and sent.
            // This example assumes that a file named Data.xls exists in the
            // current working directory.
            string file = "data.xls";
            // Create a message and set up the recipients.
            MailMessage message = new MailMessage(
               "jane@contoso.com",
               "ben@contoso.com",
               "Quarterly data report.",
               "See the attached spreadsheet.");

            // Create  the file attachment for this e-mail message.
            Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
            // Add time stamp information for the file.
            ContentDisposition disposition = data.ContentDisposition;
            disposition.CreationDate = System.IO.File.GetCreationTime(file);
            disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
            disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
            // Add the file attachment to this e-mail message.
            message.Attachments.Add(data);

            //Send the message.
            SmtpClient client = new SmtpClient(server);
            // Add credentials if the SMTP server requires them.
            client.Credentials = CredentialCache.DefaultNetworkCredentials;

      try {
              client.Send(message);
            }
            catch (Exception ex) {
              Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", 
                    ex.ToString() );              
            }
            // Display the values in the ContentDisposition for the attachment.
            ContentDisposition cd = data.ContentDisposition;
            Console.WriteLine("Content disposition");
            Console.WriteLine(cd.ToString());
            Console.WriteLine("File {0}", cd.FileName);
            Console.WriteLine("Size {0}", cd.Size);
            Console.WriteLine("Creation {0}", cd.CreationDate);
            Console.WriteLine("Modification {0}", cd.ModificationDate);
            Console.WriteLine("Read {0}", cd.ReadDate);
            Console.WriteLine("Inline {0}", cd.Inline);
            Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
            foreach (DictionaryEntry d in cd.Parameters)
            {
                Console.WriteLine("{0} = {1}", d.Key, d.Value);
            }
            data.Dispose();
        }
Visual C++
   static void CreateMessageWithAttachment( String^ server )
   {

      // Specify the file to be attached and sent.
      // This example assumes that a file named Data.xls exists in the
      // current working directory.
      String^ file = L"data.xls";

      // Create a message and set up the recipients.
      MailMessage^ message = gcnew MailMessage( L"jane@contoso.com",L"ben@contoso.com",L"Quarterly data report.",L"See the attached spreadsheet." );

      // Create  the file attachment for this e-mail message.
      Attachment^ data = gcnew Attachment(file, MediaTypeNames::Application::Octet);

      // Add time stamp information for the file.
      ContentDisposition^ disposition = data->ContentDisposition;
      disposition->CreationDate = System::IO::File::GetCreationTime( file );
      disposition->ModificationDate = System::IO::File::GetLastWriteTime( file );
      disposition->ReadDate = System::IO::File::GetLastAccessTime( file );

      // Add the file attachment to this e-mail message.
      message->Attachments->Add( data );

      //Send the message.
      SmtpClient^ client = gcnew SmtpClient( server );

      // Add credentials if the SMTP server requires them.
      client->Credentials = CredentialCache::DefaultNetworkCredentials;
      client->Send( message );

      // Display the values in the ContentDisposition for the attachment.
      ContentDisposition^ cd = data->ContentDisposition;
      Console::WriteLine( L"Content disposition" );
      Console::WriteLine( cd );
      Console::WriteLine( L"File {0}", cd->FileName );
      Console::WriteLine( L"Size {0}", cd->Size );
      Console::WriteLine( L"Creation {0}", cd->CreationDate );
      Console::WriteLine( L"Modification {0}", cd->ModificationDate );
      Console::WriteLine( L"Read {0}", cd->ReadDate );
      Console::WriteLine( L"Inline {0}", cd->Inline );
      Console::WriteLine( L"Parameters: {0}", cd->Parameters->Count );
      IEnumerator^ myEnum1 = cd->Parameters->GetEnumerator();
      while ( myEnum1->MoveNext() )
      {
         DictionaryEntry^ d = safe_cast<DictionaryEntry^>(myEnum1->Current);
         Console::WriteLine( L"{0} = {1}", d->Key, d->Value );
      }

      data->~Attachment();
      client->~SmtpClient();
   }


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Biblioteca de clases de .NET Framework
MailMessage (Clase)

Representa un mensaje de correo electrónico que puede enviarse mediante la clase SmtpClient.

System..::.Object
  System.Net.Mail..::.MailMessage

Espacio de nombres:  System.Net.Mail
Ensamblado:  System (en System.dll)
Visual Basic
Public Class MailMessage _
    Implements IDisposable
C#
public class MailMessage : IDisposable
Visual C++
public ref class MailMessage : IDisposable
F#
type MailMessage =  
    class
        interface IDisposable
    end

El tipo MailMessage expone los siguientes miembros.

  NombreDescripción
Método públicoMailMessage()()()Inicializa una instancia vacía de la clase MailMessage.
Método públicoMailMessage(MailAddress, MailAddress)Inicializa una nueva instancia de la clase MailMessage utilizando los objetos especificados de clase MailAddress.
Método públicoMailMessage(String, String)Inicializa una nueva instancia de la clase MailMessage utilizando los objetos especificados de la clase String.
Método públicoMailMessage(String, String, String, String)Inicializa una nueva instancia de la clase MailMessage.
Arriba
  NombreDescripción
Propiedad públicaAlternateViewsObtiene la colección de datos adjuntos que se utiliza para almacenar formatos alternativos del cuerpo del mensaje.
Propiedad públicaAttachmentsObtiene la colección de datos adjuntos que se utiliza para almacenar los datos adjuntos a este mensaje de correo electrónico.
Propiedad públicaBccObtiene la colección de direcciones que contiene los destinatarios ocultos de copia (CCO) de este mensaje de correo electrónico.
Propiedad públicaBodyObtiene o establece el cuerpo del mensaje.
Propiedad públicaBodyEncodingObtiene o establece la codificación que se utiliza para codificar el cuerpo del mensaje.
Propiedad públicaCCObtiene la colección de direcciones que contiene los destinatarios para recibir copia (CC) de este mensaje de correo electrónico.
Propiedad públicaDeliveryNotificationOptionsObtiene o establece las notificaciones de entrega este mensaje de correo electrónico.
Propiedad públicaFromObtiene o establece la dirección De de este mensaje de correo electrónico.
Propiedad públicaHeadersObtiene los encabezados de correo electrónico que se transmiten con este mensaje de correo electrónico.
Propiedad públicaHeadersEncodingObtiene o establece la codificación que se usa para los encabezados personalizados definidos por el usuario de este mensaje de correo electrónico.
Propiedad públicaIsBodyHtmlObtiene o establece un valor que indica si el cuerpo del mensaje de correo está en HTML.
Propiedad públicaPriorityObtiene o establece la prioridad del mensaje de correo electrónico.
Propiedad públicaReplyTo Obsoleto. Obtiene o establece la dirección de origen o de respuesta del mensaje de correo.
Propiedad públicaReplyToListObtiene o establece la lista de direcciones a las que se va a enviar una respuesta al mensaje de correo.
Propiedad públicaSenderObtiene o establece la dirección del remitente de este mensaje de correo electrónico.
Propiedad públicaSubjectObtiene o establece la línea de asunto de este mensaje de correo electrónico.
Propiedad públicaSubjectEncodingObtiene o establece la codificación utilizada para el contenido del asunto de este mensaje de correo electrónico.
Propiedad públicaToObtiene la colección de direcciones que contiene los destinatarios de este mensaje de correo electrónico.
Arriba
  NombreDescripción
Método públicoDispose()()()Libera todos los recursos utilizados por el objeto MailMessage.
Método protegidoDispose(Boolean)Libera los recursos no administrados usados por MailMessage y, opcionalmente, los recursos administrados.
Método públicoEquals(Object)Determina si el objeto Object especificado es igual al objeto Object actual. (Se hereda de Object).
Método protegidoFinalizePermite que un objeto intente liberar recursos y realizar otras operaciones de limpieza antes de ser reclamado por la recolección de elementos no utilizados. (Se hereda de Object).
Método públicoGetHashCodeActúa como función hash para un tipo concreto. (Se hereda de Object).
Método públicoGetTypeObtiene el objeto Type de la instancia actual. (Se hereda de Object).
Método protegidoMemberwiseCloneCrea una copia superficial del objeto Object actual. (Se hereda de Object).
Método públicoToStringDevuelve una cadena que representa el objeto actual. (Se hereda de Object).
Arriba

Se utilizan instancias de la clase MailMessage para crear mensajes de correo electrónico que se transmiten a un servidor SMTP para entregarse mediante la clase SmtpClient.

El remitente, destinatario, asunto y cuerpo de un mensaje de correo electrónico se pueden especificar como parámetros cuando MailMessage se usa para inicializar un objeto MailMessage. Estos parámetros se pueden establecer o también obtener acceso a ellos usando las propiedades en el objeto MailMessage.

Los encabezados y elementos primarios de mensajes de correo del mensaje se pueden establecer usando las siguientes propiedades de la clase MailMessage.

Encabezado de mensaje o parte

Propiedad

Datos adjuntos

Attachments

Copias ocultas (CCO)

Bcc

Copias (CC)

CC

Content-Type

BodyEncoding

Codificar encabezados personalizados

HeadersEncoding

Cuerpo del mensaje

Body

Prioridad

Priority

Destinatario

To

Responder a

ReplyToList

Remitente

From

Subject

Subject

La clase MailMessage también permite a una aplicación tener acceso a la colección de encabezados para el mensaje usando la propiedad Headers. Aunque esta colección es de solo lectura (no se puede establecer una nueva colección), los encabezados personalizados se pueden agregar o eliminar de esta colección. Cualquier encabezado personalizado agregado estará incluido cuando se envía la instancia MailMessage. Antes de que se envíe un mensaje, solo los encabezados específicamente agregados a esta colección en la propiedad Headers están incluidos en la colección. Después de enviar la instancia de MailMessage, la propiedad Headers también incluirá los encabezados que se establecen usando las propiedades asociadas de la clase MailMessage o parámetros pasados cuando MailMessage se usa para inicializar un objeto MailMessage.

Si algunos encabezados de mensaje son incorrectos, podrían hacer que se dañase el mensaje de correo electrónico. Así que cualquier encabezado de mensaje en la colección de encabezados que se puede establecer usando una propiedad en la clase MailMessage solo se debería establecer usando la propiedad de la clase MailMessage o como un parámetro pasado cuando MailMessage inicializa un objeto MailMessage. La siguiente lista de encabezados de mensaje no se debería agregar usando la propiedad Headers y cualquier valor establecido para estos encabezados usando la propiedad Headers se descartará o se sobrescribirá cuando se envíe el mensaje:

  • CCO

  • CC

  • Content-ID

  • Content-Location

  • Content-Transfer-Encoding

  • Content-Type

  • Fecha

  • From

  • Importancia

  • Versión de MIME

  • Prioridad

  • Responder a

  • Remitente

  • Para

  • Prioridad X

Si la aplicación no especifica un encabezado del Remitente X usando la propiedad Headers, la clase MailMessage creará uno cuando se envía el mensaje.

Utilice la propiedad AlternateViews para especificar distintos formatos para las copias de un mensaje de correo electrónico. Por ejemplo, si envía un mensaje en HTML y algunos de los destinatarios utilizan lectores de correo que no pueden mostrar contenido HTML, es probable que también desee proporcionar una versión de texto sin formato. Para obtener un ejemplo sobre la forma crear un mensaje con vistas alternativas, vea AlternateViews.

Use la propiedad Attachments para agregar datos adjuntos a un mensaje de correo electrónico. Para obtener un ejemplo sobre la forma crear un mensaje con datos adjuntos, vea Attachments.

Después de crear el mensaje de correo electrónico, puede enviarlo utilizando los métodos Send o SendAsync.

En el siguiente ejemplo de código se muestra la forma de crear y enviar un mensaje de correo electrónico con datos adjuntos.

C#
        public static void CreateMessageWithAttachment(string server)
        {
            // Specify the file to be attached and sent.
            // This example assumes that a file named Data.xls exists in the
            // current working directory.
            string file = "data.xls";
            // Create a message and set up the recipients.
            MailMessage message = new MailMessage(
               "jane@contoso.com",
               "ben@contoso.com",
               "Quarterly data report.",
               "See the attached spreadsheet.");

            // Create  the file attachment for this e-mail message.
            Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
            // Add time stamp information for the file.
            ContentDisposition disposition = data.ContentDisposition;
            disposition.CreationDate = System.IO.File.GetCreationTime(file);
            disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
            disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
            // Add the file attachment to this e-mail message.
            message.Attachments.Add(data);

            //Send the message.
            SmtpClient client = new SmtpClient(server);
            // Add credentials if the SMTP server requires them.
            client.Credentials = CredentialCache.DefaultNetworkCredentials;

      try {
              client.Send(message);
            }
            catch (Exception ex) {
              Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", 
                    ex.ToString() );              
            }
            // Display the values in the ContentDisposition for the attachment.
            ContentDisposition cd = data.ContentDisposition;
            Console.WriteLine("Content disposition");
            Console.WriteLine(cd.ToString());
            Console.WriteLine("File {0}", cd.FileName);
            Console.WriteLine("Size {0}", cd.Size);
            Console.WriteLine("Creation {0}", cd.CreationDate);
            Console.WriteLine("Modification {0}", cd.ModificationDate);
            Console.WriteLine("Read {0}", cd.ReadDate);
            Console.WriteLine("Inline {0}", cd.Inline);
            Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
            foreach (DictionaryEntry d in cd.Parameters)
            {
                Console.WriteLine("{0} = {1}", d.Key, d.Value);
            }
            data.Dispose();
        }
Visual C++
   static void CreateMessageWithAttachment( String^ server )
   {

      // Specify the file to be attached and sent.
      // This example assumes that a file named Data.xls exists in the
      // current working directory.
      String^ file = L"data.xls";

      // Create a message and set up the recipients.
      MailMessage^ message = gcnew MailMessage( L"jane@contoso.com",L"ben@contoso.com",L"Quarterly data report.",L"See the attached spreadsheet." );

      // Create  the file attachment for this e-mail message.
      Attachment^ data = gcnew Attachment(file, MediaTypeNames::Application::Octet);

      // Add time stamp information for the file.
      ContentDisposition^ disposition = data->ContentDisposition;
      disposition->CreationDate = System::IO::File::GetCreationTime( file );
      disposition->ModificationDate = System::IO::File::GetLastWriteTime( file );
      disposition->ReadDate = System::IO::File::GetLastAccessTime( file );

      // Add the file attachment to this e-mail message.
      message->Attachments->Add( data );

      //Send the message.
      SmtpClient^ client = gcnew SmtpClient( server );

      // Add credentials if the SMTP server requires them.
      client->Credentials = CredentialCache::DefaultNetworkCredentials;
      client->Send( message );

      // Display the values in the ContentDisposition for the attachment.
      ContentDisposition^ cd = data->ContentDisposition;
      Console::WriteLine( L"Content disposition" );
      Console::WriteLine( cd );
      Console::WriteLine( L"File {0}", cd->FileName );
      Console::WriteLine( L"Size {0}", cd->Size );
      Console::WriteLine( L"Creation {0}", cd->CreationDate );
      Console::WriteLine( L"Modification {0}", cd->ModificationDate );
      Console::WriteLine( L"Read {0}", cd->ReadDate );
      Console::WriteLine( L"Inline {0}", cd->Inline );
      Console::WriteLine( L"Parameters: {0}", cd->Parameters->Count );
      IEnumerator^ myEnum1 = cd->Parameters->GetEnumerator();
      while ( myEnum1->MoveNext() )
      {
         DictionaryEntry^ d = safe_cast<DictionaryEntry^>(myEnum1->Current);
         Console::WriteLine( L"{0} = {1}", d->Key, d->Value );
      }

      data->~Attachment();
      client->~SmtpClient();
   }


.NET Framework

Compatible con: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1

Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
Todos los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker