Condividi tramite


SmtpClient.SendAsync Metodo

Definizione

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

Overload

Nome Descrizione
SendAsync(MailMessage, Object)

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

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

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

SendAsync(MailMessage, Object)

Origine:
SmtpClient.cs
Origine:
SmtpClient.cs
Origine:
SmtpClient.cs
Origine:
SmtpClient.cs
Origine:
SmtpClient.cs

Invia il messaggio di posta elettronica specificato a un server SMTP per il recapito. Questo metodo non blocca il thread chiamante e consente al chiamante di passare un oggetto al metodo richiamato al termine 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

Oggetto 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 sono specificati destinatari nelle Toproprietà , CCe Bcc .

oppure

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

oppure

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

oppure

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

Questo oggetto è stato eliminato.

Connessione al server SMTP non riuscita.

oppure

Autenticazione non riuscita.

oppure

Timeout dell'operazione.

oppure

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

oppure

EnableSsl è impostato su true, ma il server di posta SMTP non ha annunciato STARTTLS nella risposta al comando EHLO.

oppure

Impossibile recapitare l'oggetto message a uno o più destinatari in To, CCo Bcc.

Impossibile recapitare l'oggetto message a uno dei destinatari in To, CCo Bcc.

Impossibile recapitare l'oggetto message a due o più destinatari in To, CCo Bcc.

Esempio

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


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)
            {
                client.SendAsyncCancel();
            }
            // Clean up.
            message.Dispose();
            client.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()
            client.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 di 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 le 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 inoltre contenere un'eccezione interna che indica il motivo per cui l'operazione non è riuscita.

Quando si invia un messaggio di posta elettronica utilizzando SendAsync 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 è possibile 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 .

Annotazioni

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)

Origine:
SmtpClient.cs
Origine:
SmtpClient.cs
Origine:
SmtpClient.cs
Origine:
SmtpClient.cs
Origine:
SmtpClient.cs

Invia un messaggio di posta elettronica a un server SMTP per il recapito. Il mittente del messaggio, i destinatari, l'oggetto e il corpo del messaggio vengono specificati utilizzando String oggetti . Questo metodo non blocca il thread chiamante e consente al chiamante di passare un oggetto al metodo richiamato al termine 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

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

recipients
String

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

subject
String

Oggetto String contenente la riga dell'oggetto per il messaggio.

body
String

Oggetto 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

recipients è null.

from è Empty.

oppure

recipients è Empty.

Si SmtpClient tratta di una SendAsync chiamata in corso.

oppure

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

oppure

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

oppure

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

Questo oggetto è stato eliminato.

Connessione al server SMTP non riuscita.

oppure

Autenticazione non riuscita.

oppure

Timeout dell'operazione.

oppure

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

oppure

EnableSsl è impostato su true, ma il server di posta SMTP non ha annunciato STARTTLS nella risposta al comando EHLO.

oppure

Impossibile recapitare il messaggio a uno o più destinatari in recipients.

Impossibile recapitare il messaggio a uno dei destinatari in To, CCo Bcc.

Impossibile recapitare il messaggio a due o più destinatari in To, CCo 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 di 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 le credenziali, è necessario impostarle prima di chiamare questo metodo. Per specificare le credenziali, utilizzare 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 inoltre contenere un'eccezione interna che indica il motivo per cui l'operazione non è riuscita.

Quando si invia un messaggio di posta elettronica utilizzando SendAsync 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 è possibile 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 .

Annotazioni

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