SmtpClient.SendAsync Método

Definición

Envía un mensaje de correo electrónico. Estos métodos no bloquean el subproceso que realiza la llamada.

Sobrecargas

SendAsync(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.

SendAsync(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.

SendAsync(MailMessage, Object)

Source:
SmtpClient.cs
Source:
SmtpClient.cs
Source:
SmtpClient.cs

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.

public:
 void SendAsync(System::Net::Mail::MailMessage ^ message, System::Object ^ userToken);
public void SendAsync (System.Net.Mail.MailMessage message, object? userToken);
public void SendAsync (System.Net.Mail.MailMessage message, object userToken);
member this.SendAsync : System.Net.Mail.MailMessage * obj -> unit
Public Sub SendAsync (message As MailMessage, userToken As Object)

Parámetros

message
MailMessage

Objeto MailMessage que contiene el mensaje que se va a enviar.

userToken
Object

Objeto definido por el usuario que se pasa al método invocado cuando se completa la operación asincrónica.

Excepciones

message es null.

o bien

From es null.

Tiene SmtpClient otra operación de envío que ya está en curso.

o bien

No hay ningún destinatario especificado en las propiedades To, CC y Bcc

o bien

La propiedad DeliveryMethod se establece en Network y Host es null.

o bien

La propiedad DeliveryMethod se establece en Network y Hostes igual a la cadena vacía ("").

o bien

La propiedad DeliveryMethod se establece en Network y Port es cero, un número negativo o mayor que 65.535.

Este objeto se ha eliminado.

Se ha producido un error de conexión al servidor SMTP.

o bien

Error de autenticación.

o bien

La operación agotó el tiempo de espera.

o bien

EnableSsl se establece en true pero la propiedad DeliveryMethod se establece en SpecifiedPickupDirectory o PickupDirectoryFromIis.

o bien

EnableSsl está establecido en true, pero el servidor de correo de SMTP no anunció STARTTLS en la respuesta al comando EHLO.

o bien

No se pudo entregar message a uno o varios de los destinatarios de To, CC o Bcc.

No se pudo entregar message a uno de los destinatarios en To, CC o Bcc.

No se pudo entregar message a dos o más de los destinatarios en To, CC o Bcc.

Ejemplos

En el ejemplo de código siguiente se muestra cómo llamar a este método.

#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 be the SMTP host.
        SmtpClient^ client = gcnew SmtpClient(args[1]);
        // Specify the email 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 email message.
        MailAddress^ to = gcnew MailAddress("ben@contoso.com");
        // Specify the message content.
        MailMessage^ message = gcnew MailMessage(from, to);
        message->Body = "This is a test email 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!");
    }
}

using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
namespace Examples.SmtpExamples.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 be the SMTP host.
            SmtpClient client = new SmtpClient(args[0]);
            // Specify the email 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 email message.
            MailAddress to = new MailAddress("ben@contoso.com");
            // Specify the message content.
            MailMessage message = new MailMessage(from, to);
            message.Body = "This is a test email 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.");
        }
    }
}

Imports System.Net
Imports System.Net.Mail
Imports System.Net.Mime
Imports System.Threading
Imports System.ComponentModel

Namespace Examples.SmtpExamples.Async
    Public Class SimpleAsynchronousExample
        Private Shared mailSent As Boolean = False
        Private Shared Sub SendCompletedCallback(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
            ' Get the unique identifier for this asynchronous operation.
            Dim token As String = CStr(e.UserState)

            If e.Cancelled Then
                Console.WriteLine("[{0}] Send canceled.", token)
            End If
            If e.Error IsNot Nothing Then
                Console.WriteLine("[{0}] {1}", token, e.Error.ToString())
            Else
                Console.WriteLine("Message sent.")
            End If
            mailSent = True
        End Sub
        Public Shared Sub Main(ByVal args() As String)
            ' Command line argument must the SMTP host.
            Dim client As New SmtpClient(args(0))
            ' Specify the email sender.
            ' Create a mailing address that includes a UTF8 character
            ' in the display name.
            Dim mailFrom As New MailAddress("jane@contoso.com", "Jane " & ChrW(&HD8) & " Clayton", System.Text.Encoding.UTF8)
            ' Set destinations for the email message.
            Dim mailTo As New MailAddress("ben@contoso.com")
            ' Specify the message content.
            Dim message As New MailMessage(mailFrom, mailTo)
            message.Body = "This is a test email message sent by an application. "
            ' Include some non-ASCII characters in body and subject.
            Dim someArrows As New String(New Char() {ChrW(&H2190), ChrW(&H2191), ChrW(&H2192), ChrW(&H2193)})
            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.
            AddHandler client.SendCompleted, AddressOf 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.
            Dim userState As String = "test message1"
            client.SendAsync(message, userState)
            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.")
            Dim answer As String = Console.ReadLine()
            ' If the user canceled the send, and mail hasn't been sent yet,
            ' then cancel the pending operation.
            If answer.StartsWith("c") AndAlso mailSent = False Then
                client.SendAsyncCancel()
            End If
            ' Clean up.
            message.Dispose()
            Console.WriteLine("Goodbye.")
        End Sub
    End Class
End Namespace

Comentarios

Para recibir una notificación cuando se ha enviado el correo electrónico o se ha cancelado la operación, agregue un controlador de eventos al SendCompleted evento. Puede cancelar una SendAsync operación llamando al SendAsyncCancel método .

Después de llamar a SendAsync, debe esperar a que se complete la transmisión de correo electrónico antes de intentar enviar otro mensaje de correo electrónico mediante Send o SendAsync.

Antes de llamar a este método, y HostPort se deben establecer a través de los archivos de configuración estableciendo las propiedades pertinentes o pasando esta información al SmtpClient(String, Int32) constructor.

Si el host SMTP requiere credenciales, debe establecerlas antes de llamar a este método. Para especificar las credenciales, use las UseDefaultCredentials propiedades o Credentials .

Si recibe una SmtpException excepción, compruebe la StatusCode propiedad para encontrar el motivo por el que se produjo un error en la operación. SmtpException También puede contener una excepción interna que indica el motivo por el que se produjo un error en la operación.

Al enviar correo electrónico mediante SendAsync a varios destinatarios, si el servidor SMTP acepta algunos destinatarios como válidos y rechaza otros, se produce una SmtpException excepción con para NullReferenceException la excepción interna. Si esto ocurre, SendAsync no se puede enviar correo electrónico a cualquiera de los destinatarios.

La aplicación puede detectar un error de validación de certificados de servidor examinando la Error propiedad pasada al SendCompletedEventHandler delegado.

La Timeout propiedad no tiene ningún efecto en una SendAsync llamada.

Para enviar correo y bloquear mientras se transmite al servidor SMTP, use uno de los Send métodos .

Nota

Si la EnableSsl propiedad se establece trueen y el servidor de correo SMTP no anuncia STARTTLS en la respuesta al comando EHLO, una llamada a los Send métodos o SendAsync producirá una SmtpExceptionexcepción .

Se aplica a

SendAsync(String, String, String, String, Object)

Source:
SmtpClient.cs
Source:
SmtpClient.cs
Source:
SmtpClient.cs

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.

public:
 void SendAsync(System::String ^ from, System::String ^ recipients, System::String ^ subject, System::String ^ body, System::Object ^ userToken);
public void SendAsync (string from, string recipients, string? subject, string? body, object? userToken);
public void SendAsync (string from, string recipients, string subject, string body, object userToken);
member this.SendAsync : string * string * string * string * obj -> unit
Public Sub SendAsync (from As String, recipients As String, subject As String, body As String, userToken As Object)

Parámetros

from
String

Objeto String que contiene la información de dirección del remitente del mensaje.

recipients
String

Objeto String que contiene la dirección a la que se envía el mensaje.

subject
String

Objeto String que contiene la línea de asunto del mensaje.

body
String

Objeto String que contiene el cuerpo del mensaje.

userToken
Object

Objeto definido por el usuario que se pasa al método invocado cuando se completa la operación asincrónica.

Excepciones

from es null.

o bien

recipient es null.

from es Empty.

o bien

recipient es Empty.

Este objeto SmtpClient tiene una llamada a SendAsync en curso.

o bien

La propiedad DeliveryMethod se establece en Network y Host es null.

o bien

La propiedad DeliveryMethod se establece en Network y Hostes igual a la cadena vacía ("").

o bien

La propiedad DeliveryMethod se establece en Network y Port es cero, un número negativo o mayor que 65.535.

Este objeto se ha eliminado.

Se ha producido un error de conexión al servidor SMTP.

o bien

Error de autenticación.

o bien

La operación agotó el tiempo de espera.

o bien

EnableSsl se establece en true pero la propiedad DeliveryMethod se establece en SpecifiedPickupDirectory o PickupDirectoryFromIis.

o bien

EnableSsl está establecido en true, pero el servidor de correo de SMTP no anunció STARTTLS en la respuesta al comando EHLO.

o bien

No se ha podido entregar el mensaje a uno o varios de los destinatarios de recipients.

No se pudo entregar message a uno de los destinatarios en To, CC o Bcc.

No se pudo entregar message a dos o más de los destinatarios en To, CC o Bcc.

Comentarios

Para recibir una notificación cuando se ha enviado el correo electrónico o se ha cancelado la operación, agregue un controlador de eventos al SendCompleted evento. Puede cancelar una SendAsync operación llamando al SendAsyncCancel método .

Después de llamar a SendAsync, debe esperar a que se complete la transmisión de correo electrónico antes de intentar enviar otro mensaje de correo electrónico mediante Send o SendAsync.

Antes de llamar a este método, las Host propiedades y Port deben establecerse a través de los archivos de configuración o estableciendo las propiedades o pasando esta información al SmtpClient(String, Int32) constructor.

Si el host SMTP requiere credenciales, debe establecerlas antes de llamar a este método. Para especificar las credenciales, use la UseDefaultCredentials propiedad o Credentials .

Si recibe una SmtpException excepción, compruebe la StatusCode propiedad para encontrar el motivo por el que se produjo un error en la operación. SmtpException También puede contener una excepción interna que indica el motivo por el que se produjo un error en la operación.

Al enviar correo electrónico mediante SendAsync a varios destinatarios, si el servidor SMTP acepta algunos destinatarios como válidos y rechaza otros, se produce una SmtpException excepción con para NullReferenceException la excepción interna. Si esto ocurre, SendAsync no se puede enviar correo electrónico a cualquiera de los destinatarios.

La aplicación puede detectar un error de validación de certificados de servidor examinando la Error propiedad pasada al SendCompletedEventHandler delegado.

La Timeout propiedad no tiene ningún efecto en una SendAsync llamada.

Para enviar correo y bloquear mientras se transmite al servidor SMTP, use uno de los Send métodos .

Nota

Si la EnableSsl propiedad se establece trueen y el servidor de correo SMTP no anuncia STARTTLS en la respuesta al comando EHLO, una llamada a los Send métodos o SendAsync producirá una SmtpExceptionexcepción .

Se aplica a