SmtpClient.SendAsync Metodo

Definizione

Invia un messaggio di posta elettronica. Questi metodi non bloccano il thread chiamante.

Overload

SendAsync(MailMessage, Object)

Invia il messaggio di posta elettronica specificato a un server SMTP per la consegna. Questo metodo non blocca il thread chiamante e consente al chiamante di passare un oggetto al metodo richiamato al completamento dell'operazione.

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

Invia un messaggio di posta elettronica a un server SMTP per la consegna. Il mittente, i destinatari, l'oggetto e il corpo del messaggio vengono specificati mediante gli oggetti String. Questo metodo non blocca il thread chiamante e consente al chiamante di passare un oggetto al metodo richiamato al completamento dell'operazione.

SendAsync(MailMessage, Object)

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

Invia il messaggio di posta elettronica specificato a un server SMTP per la consegna. Questo metodo non blocca il thread chiamante e consente al chiamante di passare un oggetto al metodo richiamato al completamento dell'operazione.

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)

Parametri

message
MailMessage

Classe MailMessage contenente il messaggio da inviare.

userToken
Object

Oggetto definito dall'utente passato al metodo richiamato al completamento dell'operazione asincrona.

Eccezioni

message è null.

-oppure-

From è null.

È SmtpClient già in corso un'altra operazione di invio.

-oppure-

Non esistono destinatari specificati nelle proprietà To, CC e Bcc.

-oppure-

La proprietà DeliveryMethod è impostata su Network e Host è null.

-oppure-

La proprietà DeliveryMethod è impostata su Network e Host è uguale alla stringa vuota ("").

-oppure-

proprietà DeliveryMethod è impostata su Network e Port è zero, un numero negativo o maggiore di 65.535.

L'oggetto è stato eliminato.

La connessione al server SMTP ha avuto esito negativo.

-oppure-

Autenticazione non riuscita.

-oppure-

Timeout dell'operazione.

-oppure-

EnableSsl è impostato su true ma la proprietà DeliveryMethod è impostata su SpecifiedPickupDirectory o PickupDirectoryFromIis.

-oppure-

EnableSsl viene impostato su true, ma il server di posta SMTP non annuncia STARTTLS nella risposta al comando EHLO.

-oppure-

Non è possibile recapitare message a uno o più destinatari in To, CC o Bcc.

Non è possibile recapitare message a uno dei destinatari in To, CC o Bcc.

Non è possibile recapitare message a due o più destinatari in To, CC o Bcc.

Esempio

Nell'esempio di codice seguente viene illustrata la chiamata a questo metodo.

#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

Commenti

Per ricevere una notifica quando il messaggio di posta elettronica è stato inviato o l'operazione è stata annullata, aggiungere un gestore eventi all'evento SendCompleted . È possibile annullare un'operazione SendAsync chiamando il SendAsyncCancel metodo .

Dopo aver chiamato SendAsync, è necessario attendere il completamento della trasmissione della posta elettronica prima di tentare di inviare un altro messaggio di posta elettronica usando Send o SendAsync.

Prima di chiamare questo metodo, Host e Port deve essere impostato tramite i file di configurazione impostando le proprietà pertinenti o passando queste informazioni nel SmtpClient(String, Int32) costruttore.

Se l'host SMTP richiede credenziali, è necessario impostarle prima di chiamare questo metodo. Per specificare le credenziali, usare le UseDefaultCredentials proprietà o Credentials .

Se si riceve un'eccezione SmtpException , controllare la StatusCode proprietà per trovare il motivo per cui l'operazione non è riuscita. Può SmtpException anche contenere un'eccezione interna che indica il motivo per cui l'operazione non è riuscita.

Quando si invia un messaggio di posta elettronica utilizzando SendAsync a più destinatari, se il server SMTP accetta alcuni destinatari come validi e rifiuta altri, viene generata un'eccezione SmtpExceptionNullReferenceException per l'eccezione interna. In questo caso, SendAsync non riesce a inviare messaggi di posta elettronica a uno dei destinatari.

L'applicazione può rilevare un errore di convalida del certificato server esaminando la Error proprietà passata al SendCompletedEventHandler delegato.

La Timeout proprietà non ha alcun effetto su una SendAsync chiamata.

Per inviare messaggi e bloccare mentre viene trasmesso al server SMTP, utilizzare uno dei Send metodi .

Nota

Se la EnableSsl proprietà è impostata su truee il server di posta SMTP non annuncia STARTTLS nella risposta al comando EHLO, una chiamata ai Send metodi o SendAsync genererà un'eccezione SmtpException.

Si applica a

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

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

Invia un messaggio di posta elettronica a un server SMTP per la consegna. Il mittente, i destinatari, l'oggetto e il corpo del messaggio vengono specificati mediante gli oggetti String. Questo metodo non blocca il thread chiamante e consente al chiamante di passare un oggetto al metodo richiamato al completamento dell'operazione.

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)

Parametri

from
String

Classe String contenente le informazioni sull'indirizzo del mittente del messaggio.

recipients
String

Classe String contenente l'indirizzo a cui viene inviato il messaggio.

subject
String

Classe String contenente l'oggetto del messaggio.

body
String

Classe String contenente il corpo del messaggio.

userToken
Object

Oggetto definito dall'utente passato al metodo richiamato al completamento dell'operazione asincrona.

Eccezioni

from è null.

-oppure-

recipient è null.

from è Empty.

-oppure-

recipient è Empty.

È in corso una chiamata a SmtpClient da parte della classe SendAsync.

-oppure-

La proprietà DeliveryMethod è impostata su Network e Host è null.

-oppure-

La proprietà DeliveryMethod è impostata su Network e Host è uguale alla stringa vuota ("").

-oppure-

proprietà DeliveryMethod è impostata su Network e Port è zero, un numero negativo o maggiore di 65.535.

L'oggetto è stato eliminato.

La connessione al server SMTP ha avuto esito negativo.

-oppure-

Autenticazione non riuscita.

-oppure-

Timeout dell'operazione.

-oppure-

EnableSsl è impostato su true ma la proprietà DeliveryMethod è impostata su SpecifiedPickupDirectory o PickupDirectoryFromIis.

-oppure-

EnableSsl viene impostato su true, ma il server di posta SMTP non annuncia STARTTLS nella risposta al comando EHLO.

-oppure-

Non è possibile recapitare il messaggio a uno o più destinatari in recipients.

Non è possibile recapitare message a uno dei destinatari in To, CC o Bcc.

Non è possibile recapitare message a due o più destinatari in To, CC o Bcc.

Commenti

Per ricevere una notifica quando il messaggio di posta elettronica è stato inviato o l'operazione è stata annullata, aggiungere un gestore eventi all'evento SendCompleted . È possibile annullare un'operazione SendAsync chiamando il SendAsyncCancel metodo .

Dopo aver chiamato SendAsync, è necessario attendere il completamento della trasmissione della posta elettronica prima di tentare di inviare un altro messaggio di posta elettronica usando Send o SendAsync.

Prima di chiamare questo metodo, le Host proprietà e Port devono essere impostate tramite i file di configurazione o impostando le proprietà o passando queste informazioni nel SmtpClient(String, Int32) costruttore.

Se l'host SMTP richiede credenziali, è necessario impostarle prima di chiamare questo metodo. Per specificare le credenziali, usare la UseDefaultCredentials proprietà o Credentials .

Se si riceve un'eccezione SmtpException , controllare la StatusCode proprietà per trovare il motivo per cui l'operazione non è riuscita. Può SmtpException anche contenere un'eccezione interna che indica il motivo per cui l'operazione non è riuscita.

Quando si invia un messaggio di posta elettronica a SendAsync più destinatari, se il server SMTP accetta alcuni destinatari come validi e rifiuta altri utenti, viene SmtpException generato un oggetto con un'eccezione NullReferenceException interna. In questo caso, SendAsync non riesce a inviare messaggi di posta elettronica a uno dei destinatari.

L'applicazione può rilevare un errore di convalida del certificato server esaminando la Error proprietà passata al SendCompletedEventHandler delegato.

La Timeout proprietà non ha alcun effetto su una SendAsync chiamata.

Per inviare posta elettronica e bloccare mentre viene trasmesso al server SMTP, usare uno dei Send metodi.

Nota

Se la EnableSsl proprietà è impostata su truee il server di posta SMTP non annuncia STARTTLS nella risposta al comando EHLO, verrà generata una SmtpExceptionchiamata ai Send metodi o SendAsync .

Si applica a