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

Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).

System..::.Object
  System.Net.Mail..::.SmtpClient

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

The SmtpClient type exposes the following members.

  NameDescription
Public methodSmtpClient()()()Initializes a new instance of the SmtpClient class by using configuration file settings.
Public methodSmtpClient(String)Initializes a new instance of the SmtpClient class that sends e-mail by using the specified SMTP server.
Public methodSmtpClient(String, Int32)Initializes a new instance of the SmtpClient class that sends e-mail by using the specified SMTP server and port.
Top
  NameDescription
Public propertyClientCertificatesSpecify which certificates should be used to establish the Secure Sockets Layer (SSL) connection.
Public propertyCredentialsGets or sets the credentials used to authenticate the sender.
Public propertyDeliveryMethodSpecifies how outgoing email messages will be handled.
Public propertyEnableSslSpecify whether the SmtpClient uses Secure Sockets Layer (SSL) to encrypt the connection.
Public propertyHostGets or sets the name or IP address of the host used for SMTP transactions.
Public propertyPickupDirectoryLocationGets or sets the folder where applications save mail messages to be processed by the local SMTP server.
Public propertyPortGets or sets the port used for SMTP transactions.
Public propertyServicePointGets the network connection used to transmit the e-mail message.
Public propertyTargetNameGets or sets the Service Provider Name (SPN) to use for authentication when using extended protection.
Public propertyTimeoutGets or sets a value that specifies the amount of time after which a synchronous Send call times out.
Public propertyUseDefaultCredentialsGets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.
Top
  NameDescription
Public methodDispose()()()Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, and releases all resources used by the current instance of the SmtpClient class.
Protected methodDispose(Boolean)Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, releases all resources used by the current instance of the SmtpClient class, and optionally disposes of 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.)
Protected methodOnSendCompletedRaises the SendCompleted event.
Public methodSend(MailMessage)Sends the specified message to an SMTP server for delivery.
Public methodSend(String, String, String, String)Sends the specified e-mail message to an SMTP server for delivery. The message sender, recipients, subject, and message body are specified using String objects.
Public methodSendAsync(MailMessage, Object)Sends the specified e-mail message to an SMTP server for delivery. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes.
Public methodSendAsync(String, String, String, String, Object)Sends an e-mail message to an SMTP server for delivery. The message sender, recipients, subject, and message body are specified using String objects. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes.
Public methodSendAsyncCancelCancels an asynchronous operation to send an e-mail message.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top
  NameDescription
Public eventSendCompletedOccurs when an asynchronous e-mail send operation completes.
Top

The SmtpClient class is used to send e-mail to an SMTP server for delivery. The SMTP protocol is defined in RFC 2821, which is available at http://www.ietf.org.

The classes shown in the following table are used to construct e-mail messages that can be sent using SmtpClient.

Class

Description

Attachment

Represents file attachments. This class allows you to attach files, streams, or text to an e-mail message.

MailAddress

Represents the e-mail address of the sender and recipients.

MailMessage

Represents an e-mail message.

To construct and send an e-mail message by using SmtpClient, you must specify the following information:

  • The SMTP host server that you use to send e-mail. See the Host and Port properties.

  • Credentials for authentication, if required by the SMTP server. See the Credentials property.

  • The e-mail address of the sender. See the Send and SendAsync methods that take a from parameter. Also see the MailMessage..::.From property.

  • The e-mail address or addresses of the recipients. See the Send and SendAsync methods that take a recipient parameter. Also see the MailMessage..::.To property.

  • The message content. See the Send and SendAsync methods that take a body parameter. Also see the MailMessage..::.Body property.

To include an attachment with an e-mail message, first create the attachment by using the Attachment class, and then add it to the message by using the MailMessage..::.Attachments property. Depending on the e-mail reader used by the recipients and the file type of the attachment, some recipients might not be able to read the attachment. For clients that cannot display the attachment in its original form, you can specify alternate views by using the MailMessage..::.AlternateViews property.

You can use the application or machine configuration files to specify default host, port, and credentials values for all SmtpClient objects. For more information, see <mailSettings> Element (Network Settings).

To send the e-mail message and block while waiting for the e-mail to be transmitted to the SMTP server, use one of the synchronous Send methods. To allow your program's main thread to continue executing while the e-mail is transmitted, use one of the asynchronous SendAsync methods. The SendCompleted event is raised when a SendAsync operation completes. To receive this event, you must add a SendCompletedEventHandler delegate to SendCompleted. The SendCompletedEventHandler delegate must reference a callback method that handles notification of SendCompleted events. To cancel an asynchronous e-mail transmission, use the SendAsyncCancel method.

NoteNote

If there is an e-mail transmission in progress and you call SendAsync or Send again, you will receive an InvalidOperationException.

The connection established by the current instance of the SmtpClient class to the SMTP server may be re-used if an application wishes to send multiple messages to the same SMTP server. This is particularly useful when authentication or encryption are used establish a connection to the SMTP server. The process of authenticating and establishing a TLS session can be expensive operations. A requirement to re-establish a connection for each message when sending a large quantity of email to the same SMTP server could have a significant impact on performance. There are a number of high-volume email applications that send email status updates, newsletter distributions, or email alerts. Also many email client applications support an off-line mode where users can compose many email messages that are sent later when a connection to the SMTP server is established. It is typical for an email client to send all SMTP messages to a specific SMTP server (provided by the Internet service provider) that then forwards this email to other SMTP servers.

The SmtpClient class implementation pools SMTP connections so that it can avoid the overhead of re-establishing a connection for every message to the same server. An application may re-use the same SmtpClient object to send many different emails to the same SMTP server and to many different SMTP servers. As a result, there is no way to determine when an application is finished using the SmtpClient object and it should be cleaned up.

When an SMTP session is finished and the client wishes to terminate the connection, it must send a QUIT message to the server to indicate that it has no more messages to send. This allows the server to free up resources associated with the connection from the client and process the messages which were sent by the client.

The SmtpClient class has no Finalize method, so an application must call Dispose to explicitly free up resources. The Dispose method iterates through all established connections to the SMTP server specified in the Host property and sends a QUIT message followed by gracefully ending the TCP connection. The Dispose method also releases the unmanaged resources used by the Socket and optionally disposes of the managed resources.

Call Dispose when you are finished using the SmtpClient. The Dispose method leaves the SmtpClient in an unusable state. After calling Dispose, you must release all references to the SmtpClient so the garbage collector can reclaim the memory that the SmtpClient was occupying.

TopicLocation
Cómo: Instalar y configurar servidores virtuales SMTP en IISConfigurar aplicaciones Web ASP .NET
Cómo: Instalar y configurar servidores virtuales SMTP en IIS 6.0Generar aplicaciones Web ASP .NET en Visual Studio

The following code example demonstrates sending an e-mail message asynchronously.

C#

using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
namespace Examples.SmptExamples.Async
{
    public class SimpleAsynchronousExample
    {
        static bool mailSent = false;
        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation.
             String token = (string) e.UserState;

            if (e.Cancelled)
            {
                 Console.WriteLine("[{0}] Send canceled.", token);
            }
            if (e.Error != null)
            {
                 Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
            } else
            {
                Console.WriteLine("Message sent.");
            }
            mailSent = true;
        }
        public static void Main(string[] args)
        {
            // Command line argument must the the SMTP host.
            SmtpClient client = new SmtpClient(args[0]);
            // Specify the e-mail sender.
            // Create a mailing address that includes a UTF8 character
            // in the display name.
            MailAddress from = new MailAddress("jane@contoso.com", 
               "Jane " + (char)0xD8+ " Clayton", 
            System.Text.Encoding.UTF8);
            // Set destinations for the e-mail message.
            MailAddress to = new MailAddress("ben@contoso.com");
            // Specify the message content.
            MailMessage message = new MailMessage(from, to);
            message.Body = "This is a test e-mail message sent by an application. ";
            // Include some non-ASCII characters in body and subject.
            string someArrows = new string(new char[] {'\u2190', '\u2191', '\u2192', '\u2193'});
            message.Body += Environment.NewLine + someArrows;
            message.BodyEncoding =  System.Text.Encoding.UTF8;
            message.Subject = "test message 1" + someArrows;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            // Set the method that is called back when the send operation ends.
            client.SendCompleted += new 
            SendCompletedEventHandler(SendCompletedCallback);
            // The userState can be any object that allows your callback 
            // method to identify this send operation.
            // For this example, the userToken is a string constant.
            string userState = "test message1";
            client.SendAsync(message, userState);
            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
            string answer = Console.ReadLine();
            // If the user canceled the send, and mail hasn't been sent yet,
            // then cancel the pending operation.
            if (answer.StartsWith("c") && mailSent == false)
            {
                client.SendAsyncCancel();
            }
            // Clean up.
            message.Dispose();
            Console.WriteLine("Goodbye.");
        }
    }
}
Visual C++
#using <System.dll>
using namespace System;
using namespace System::Net;
using namespace System::Net::Mail;
using namespace System::Net::Mime;
using namespace System::Threading;
using namespace System::ComponentModel;

static bool mailSent;

static void SendCompletedCallback(Object^ sender, AsyncCompletedEventArgs^ e)
{
    // Get the unique identifier for this asynchronous 
    // operation.
    String^ token = (String^) e->UserState;

    if (e->Cancelled)
    {
        Console::WriteLine("[{0}] Send canceled.", token);
    }
    if (e->Error != nullptr)
    {
        Console::WriteLine("[{0}] {1}", token, 
            e->Error->ToString());
    } else
    {
        Console::WriteLine("Message sent.");
    }
    mailSent = true;
}

int main(array<String^>^ args)
{
    if (args->Length > 1)
    {
        // Command line argument must the the SMTP host.
        SmtpClient^ client = gcnew SmtpClient(args[1]);
        // Specify the e-mail sender.
        // Create a mailing address that includes a UTF8 
        // character in the display name.
        MailAddress^ from = gcnew MailAddress("jane@contoso.com",
            "Jane " + (wchar_t)0xD8 + " Clayton",
            System::Text::Encoding::UTF8);
        // Set destinations for the e-mail message.
        MailAddress^ to = gcnew MailAddress("ben@contoso.com");
        // Specify the message content.
        MailMessage^ message = gcnew MailMessage(from, to);
        message->Body = "This is a test e-mail message sent" +
            " by an application. ";
        // Include some non-ASCII characters in body and 
        // subject.
        String^ someArrows = gcnew String(gcnew array<wchar_t>{L'\u2190', 
            L'\u2191', L'\u2192', L'\u2193'});
        message->Body += Environment::NewLine + someArrows;
        message->BodyEncoding = System::Text::Encoding::UTF8;
        message->Subject = "test message 1" + someArrows;
        message->SubjectEncoding = System::Text::Encoding::UTF8;
        // Set the method that is called back when the send
        // operation ends.
        client->SendCompleted += gcnew
            SendCompletedEventHandler(SendCompletedCallback);
        // The userState can be any object that allows your 
        // callback method to identify this send operation.
        // For this example, the userToken is a string constant.
        String^ userState = "test message1";
        client->SendAsync(message, userState);
        Console::WriteLine("Sending message... press c to" +
            " cancel mail. Press any other key to exit.");
        String^ answer = Console::ReadLine();
        // If the user canceled the send, and mail hasn't been 
        // sent yet,then cancel the pending operation.
        if (answer->ToLower()->StartsWith("c") && mailSent == false)
        {
            client->SendAsyncCancel();
        }
        // Clean up.
        delete message;
        client = nullptr;
        Console::WriteLine("Goodbye.");
    }
    else
    {
        Console::WriteLine("Please give SMTP server name!");
    }
}

.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
SmtpClient (Clase)

Permite a las aplicaciones enviar mensajes de correo electrónico mediante el protocolo SMTP (Protocolo simple de transferencia de correo).

System..::.Object
  System.Net.Mail..::.SmtpClient

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

El tipo SmtpClient expone los siguientes miembros.

  NombreDescripción
Método públicoSmtpClient()()()Inicializa una nueva instancia de la clase SmtpClient usando la configuración del archivo de configuración.
Método públicoSmtpClient(String)Inicializa una nueva instancia de la clase SmtpClient que envía correo electrónico mediante el servidor SMTP especificado.
Método públicoSmtpClient(String, Int32)Inicializa una nueva instancia de la clase SmtpClient que envía correo electrónico mediante el servidor y el puerto SMTP especificados.
Arriba
  NombreDescripción
Propiedad públicaClientCertificatesEspecifique los certificados que deben utilizarse para establecer la conexión SSL (Secure Sockets Layer).
Propiedad públicaCredentialsObtiene o establece las credenciales utilizadas para autenticar al remitente.
Propiedad públicaDeliveryMethodEspecifica la forma en que se controlarán los mensajes de correo electrónico salientes.
Propiedad públicaEnableSslEspecifique si el objeto SmtpClient utiliza SSL (Secure Sockets Layer) para cifrar la conexión.
Propiedad públicaHostObtiene o establece el nombre o la dirección IP del host que se utiliza para las transacciones SMTP.
Propiedad públicaPickupDirectoryLocationObtiene o establece la carpeta donde las aplicaciones guardan los mensajes de correo que el servidor SMTP local va a procesar.
Propiedad públicaPortObtiene o establece el puerto utilizado para las transacciones SMTP.
Propiedad públicaServicePointObtiene la conexión de red utilizada para transmitir el mensaje de correo electrónico.
Propiedad públicaTargetNameObtiene o establece el nombre del proveedor de servicios (SPN) que se utiliza para la autenticación cuando se usa la protección extendida.
Propiedad públicaTimeoutObtiene o establece un valor que especifica el intervalo de tiempo a partir del cual se considera que una llamada a Send sincrónica excede el tiempo de espera.
Propiedad públicaUseDefaultCredentialsObtiene o establece un valor Boolean que controla si se envían DefaultCredentials con las solicitudes.
Arriba
  NombreDescripción
Método públicoDispose()()()Envía un mensaje QUIT al servidor SMTP, finaliza correctamente la conexión TCP y libera todos los recursos usados por la instancia actual de la clase SmtpClient.
Método protegidoDispose(Boolean)Envía un mensaje QUIT al servidor SMTP, finaliza correctamente la conexión TCP, libera todos los recursos usados por la instancia actual de la clase SmtpClient y opcionalmente elimina 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 protegidoOnSendCompletedProvoca el evento SendCompleted.
Método públicoSend(MailMessage)Envía el mensaje especificado a un servidor SMTP para su entrega.
Método públicoSend(String, String, String, String)Envía el mensaje de correo electrónico especificado a un servidor SMTP para su entrega. El remitente del mensaje, los destinatarios, el asunto y el cuerpo del mensaje se especifican mediante objetos String.
Método públicoSendAsync(MailMessage, Object)Envía el mensaje de correo electrónico especificado a un servidor SMTP para su entrega. Este método no bloquea el subproceso que realiza la llamada y permite al llamador pasar un objeto al método que se invoca cuando termina la operación.
Método públicoSendAsync(String, String, String, String, Object)Envía un mensaje de correo electrónico a un servidor SMTP para su entrega. El remitente del mensaje, los destinatarios, el asunto y el cuerpo del mensaje se especifican mediante objetos String. Este método no bloquea el subproceso que realiza la llamada y permite al llamador pasar un objeto al método que se invoca cuando termina la operación.
Método públicoSendAsyncCancelCancela una operación asincrónica para enviar un mensaje de correo electrónico.
Método públicoToStringDevuelve una cadena que representa el objeto actual. (Se hereda de Object).
Arriba
  NombreDescripción
Evento públicoSendCompletedSe produce cuando finaliza una operación asincrónica de envío de correo electrónico.
Arriba

La clase SmtpClient se utiliza para enviar correo electrónico a un servidor SMTP para su entrega. El protocolo SMTP se define en el documento RFC 2821, que está disponible en http://www.ietf.org.

Las clases que se muestran en la siguiente tabla se utilizan para crear mensajes de correo electrónico que pueden enviarse mediante SmtpClient.

Clase

Descripción

Attachment

Representa los datos adjuntos. Esta clase le permite adjuntar archivos, secuencias o texto a un mensaje de correo electrónico.

MailAddress

Representa la dirección de correo electrónico del remitente y los destinatarios.

MailMessage

Representa un mensaje de correo electrónico.

Para crear y enviar un mensaje de correo electrónico mediante SmtpClient, deberá especificar la siguiente información:

  • El servidor host SMTP que utiliza para enviar los mensajes de correo electrónico. Vea las propiedades Host y Port.

  • Las credenciales para la autenticación, en caso de que el servidor SMTP las requiera. Vea la propiedad Credentials.

  • La dirección de correo electrónico del remitente. Vea los métodos Send y SendAsync que toman un parámetro from. Vea también la propiedad MailMessage..::.From.

  • La dirección o las direcciones de correo electrónico de los destinatarios. Vea los métodos Send y SendAsync que toman un parámetro recipient. Vea también la propiedad MailMessage..::.To.

  • El contenido del mensaje. Vea los métodos Send y SendAsync que toman un parámetro body. Vea también la propiedad MailMessage..::.Body.

Para incluir datos adjuntos en un mensaje de correo electrónico, deberá crear primero los datos adjuntos mediante la clase Attachment y, a continuación, agregarlos al mensaje mediante la propiedad MailMessage..::.Attachments. En función del lector del correo electrónico utilizado por los destinatarios y del tipo de archivo de los datos adjuntos, es posible que algunos destinatarios no puedan leer los datos adjuntos. Para los clientes que no puedan mostrar los datos adjuntos en su formato original, podrá especificar vistas alternativas mediante la propiedad MailMessage..::.AlternateViews.

Puede utilizar la aplicación o los archivos de configuración del equipo para especificar el host predeterminado, el puerto y los valores de las credenciales de todos los objetos SmtpClient. Para obtener más información, vea <mailSettings> (Elemento, Configuración de red).

Para enviar el mensaje de correo electrónico y efectuar un bloqueo mientas espera a que el correo electrónico se trasmita al servidor SMTP, utilice uno de los métodos Send sincrónicos. Para permitir que el subproceso principal de su programa siga ejecutándose mientras se transmite el correo electrónico, utilice uno de los métodos SendAsync asincrónicos. Cuando una operación SendAsync finaliza, se provoca el evento SendCompleted. Para recibir este evento, deberá agregar un delegado SendCompletedEventHandler al evento SendCompleted. El delegado SendCompletedEventHandler deberá hacer referencia a un método de devolución de llamada que controle la notificación de eventos SendCompleted. Para cancelar una transmisión de correo electrónico asincrónica, utilice el método SendAsyncCancel.

NotaNota

Si hay una transmisión de correo electrónico en curso y vuelve a llamar a SendAsync o Send, recibirá una excepción InvalidOperationException.

Se puede reutilizar la conexión establecida por la instancia actual de la clase SmtpClient en el servidor SMTP si una aplicación desea enviar varios mensajes al mismo servidor SMTP. Esto es particularmente útil cuando se usa autenticación o cifrado para establecer una conexión con el servidor SMTP. El proceso de autenticar y establecer una sesión de TLS pueden ser operaciones que consuman muchos recursos. Un requisito para restablecer una conexión para cada mensaje al enviar una cantidad grande de correo electrónico al mismo servidor SMTP pudiera tener un impacto significativo en rendimiento. Hay varias aplicaciones de correo electrónico de volumen alto que envían actualizaciones del estado del correo electrónico, distribuciones de boletín o alertas de correo electrónico. También muchas aplicaciones cliente de correo electrónico admiten un modo fuera de línea donde los usuarios pueden crear muchos mensajes de correo electrónico que se envían después cuando se establece una conexión al servidor SMTP. Es típico que un usuario de correo electrónico envíe todos los mensajes de SMTP a un servidor SMTP concreto (se proporciona por el proveedor de acceso a Internet) que después reenvía este correo electrónico a otros servidores SMTP.

La implementación de clase SmtpClient agrupa las conexiones SMTP para que pueda evitar la sobrecarga de restablecer una conexión para cada mensaje en el mismo servidor. Una aplicación puede reutilizar el mismo objeto SmtpClient para enviar muchos correos electrónicos diferentes al mismo servidor SMTP y a muchos servidores SMTP diferentes. Como resultado, no hay ninguna manera de determinar cuando una aplicación ha terminado de usar el objeto SmtpClient y se debería limpiar.

Cuando una sesión de SMTP está finalizada y el cliente desea finalizar la conexión, debe enviar un mensaje SALIR al servidor para indicar que no tiene ningún más mensaje para enviar. Esto permite al servidor liberar los recursos asociados con la conexión del cliente y procesa los mensajes que fueron enviados por el cliente.

La clase SmtpClient no tiene un método Finalize, por tanto, una aplicación debe llamar a Dispose para liberar explícitamente a los recursos. El método Dispose itera todas las conexiones establecidas con el servidor SMTP especificado en la propiedad Host y envía un mensaje QUIT seguido de la correcta finalización de la conexión TCP. El método Dispose también libera los recursos no administrados que usa el objeto Socket y, de forma opcional, desecha los recursos administrados.

Hay que llamar a Dispose cuando se deja de utilizar el objeto SmtpClient. El método Dispose deja el objeto SmtpClient en un estado no utilizable. Después de llamar a Dispose, hay que liberar todas las referencias a SmtpClient de modo que la memoria ocupada por SmtpClient pueda ser reclamada por el recolector de elementos no utilizados.

TopicLocation
Cómo: Instalar y configurar servidores virtuales SMTP en IISConfigurar aplicaciones Web ASP .NET
Cómo: Instalar y configurar servidores virtuales SMTP en IIS 6.0Generar aplicaciones Web ASP .NET en Visual Studio

En el siguiente ejemplo de código se muestra cómo enviar un mensaje de correo electrónico de forma asincrónica.

C#

using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
namespace Examples.SmptExamples.Async
{
    public class SimpleAsynchronousExample
    {
        static bool mailSent = false;
        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation.
             String token = (string) e.UserState;

            if (e.Cancelled)
            {
                 Console.WriteLine("[{0}] Send canceled.", token);
            }
            if (e.Error != null)
            {
                 Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
            } else
            {
                Console.WriteLine("Message sent.");
            }
            mailSent = true;
        }
        public static void Main(string[] args)
        {
            // Command line argument must the the SMTP host.
            SmtpClient client = new SmtpClient(args[0]);
            // Specify the e-mail sender.
            // Create a mailing address that includes a UTF8 character
            // in the display name.
            MailAddress from = new MailAddress("jane@contoso.com", 
               "Jane " + (char)0xD8+ " Clayton", 
            System.Text.Encoding.UTF8);
            // Set destinations for the e-mail message.
            MailAddress to = new MailAddress("ben@contoso.com");
            // Specify the message content.
            MailMessage message = new MailMessage(from, to);
            message.Body = "This is a test e-mail message sent by an application. ";
            // Include some non-ASCII characters in body and subject.
            string someArrows = new string(new char[] {'\u2190', '\u2191', '\u2192', '\u2193'});
            message.Body += Environment.NewLine + someArrows;
            message.BodyEncoding =  System.Text.Encoding.UTF8;
            message.Subject = "test message 1" + someArrows;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            // Set the method that is called back when the send operation ends.
            client.SendCompleted += new 
            SendCompletedEventHandler(SendCompletedCallback);
            // The userState can be any object that allows your callback 
            // method to identify this send operation.
            // For this example, the userToken is a string constant.
            string userState = "test message1";
            client.SendAsync(message, userState);
            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
            string answer = Console.ReadLine();
            // If the user canceled the send, and mail hasn't been sent yet,
            // then cancel the pending operation.
            if (answer.StartsWith("c") && mailSent == false)
            {
                client.SendAsyncCancel();
            }
            // Clean up.
            message.Dispose();
            Console.WriteLine("Goodbye.");
        }
    }
}
Visual C++
#using <System.dll>
using namespace System;
using namespace System::Net;
using namespace System::Net::Mail;
using namespace System::Net::Mime;
using namespace System::Threading;
using namespace System::ComponentModel;

static bool mailSent;

static void SendCompletedCallback(Object^ sender, AsyncCompletedEventArgs^ e)
{
    // Get the unique identifier for this asynchronous 
    // operation.
    String^ token = (String^) e->UserState;

    if (e->Cancelled)
    {
        Console::WriteLine("[{0}] Send canceled.", token);
    }
    if (e->Error != nullptr)
    {
        Console::WriteLine("[{0}] {1}", token, 
            e->Error->ToString());
    } else
    {
        Console::WriteLine("Message sent.");
    }
    mailSent = true;
}

int main(array<String^>^ args)
{
    if (args->Length > 1)
    {
        // Command line argument must the the SMTP host.
        SmtpClient^ client = gcnew SmtpClient(args[1]);
        // Specify the e-mail sender.
        // Create a mailing address that includes a UTF8 
        // character in the display name.
        MailAddress^ from = gcnew MailAddress("jane@contoso.com",
            "Jane " + (wchar_t)0xD8 + " Clayton",
            System::Text::Encoding::UTF8);
        // Set destinations for the e-mail message.
        MailAddress^ to = gcnew MailAddress("ben@contoso.com");
        // Specify the message content.
        MailMessage^ message = gcnew MailMessage(from, to);
        message->Body = "This is a test e-mail message sent" +
            " by an application. ";
        // Include some non-ASCII characters in body and 
        // subject.
        String^ someArrows = gcnew String(gcnew array<wchar_t>{L'\u2190', 
            L'\u2191', L'\u2192', L'\u2193'});
        message->Body += Environment::NewLine + someArrows;
        message->BodyEncoding = System::Text::Encoding::UTF8;
        message->Subject = "test message 1" + someArrows;
        message->SubjectEncoding = System::Text::Encoding::UTF8;
        // Set the method that is called back when the send
        // operation ends.
        client->SendCompleted += gcnew
            SendCompletedEventHandler(SendCompletedCallback);
        // The userState can be any object that allows your 
        // callback method to identify this send operation.
        // For this example, the userToken is a string constant.
        String^ userState = "test message1";
        client->SendAsync(message, userState);
        Console::WriteLine("Sending message... press c to" +
            " cancel mail. Press any other key to exit.");
        String^ answer = Console::ReadLine();
        // If the user canceled the send, and mail hasn't been 
        // sent yet,then cancel the pending operation.
        if (answer->ToLower()->StartsWith("c") && mailSent == false)
        {
            client->SendAsyncCancel();
        }
        // Clean up.
        delete message;
        client = nullptr;
        Console::WriteLine("Goodbye.");
    }
    else
    {
        Console::WriteLine("Please give SMTP server name!");
    }
}

.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