SmtpClient.SendAsync Metode

Definisi

Mengirim pesan email. Metode ini tidak memblokir utas panggilan.

Overload

SendAsync(MailMessage, Object)

Mengirim pesan email yang ditentukan ke server SMTP untuk pengiriman. Metode ini tidak memblokir utas panggilan dan memungkinkan pemanggil untuk meneruskan objek ke metode yang dipanggil ketika operasi selesai.

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

Mengirim pesan email ke server SMTP untuk pengiriman. Pengirim pesan, penerima, subjek, dan isi pesan ditentukan menggunakan String objek. Metode ini tidak memblokir utas panggilan dan memungkinkan pemanggil untuk meneruskan objek ke metode yang dipanggil ketika operasi selesai.

SendAsync(MailMessage, Object)

Sumber:
SmtpClient.cs
Sumber:
SmtpClient.cs
Sumber:
SmtpClient.cs

Mengirim pesan email yang ditentukan ke server SMTP untuk pengiriman. Metode ini tidak memblokir utas panggilan dan memungkinkan pemanggil untuk meneruskan objek ke metode yang dipanggil ketika operasi selesai.

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)

Parameter

message
MailMessage

Yang MailMessage berisi pesan yang akan dikirim.

userToken
Object

Objek yang ditentukan pengguna yang diteruskan ke metode yang dipanggil saat operasi asinkron selesai.

Pengecualian

messageadalah null.

-atau-

Fromadalah null.

Ini SmtpClient memiliki operasi pengiriman lain yang sudah berlangsung.

-atau-

Tidak ada penerima yang ditentukan dalam Toproperti , , CCdan Bcc .

-atau-

DeliveryMethod properti diatur ke Network dan Host adalah null.

-atau-

DeliveryMethod properti diatur ke Network dan Host sama dengan string kosong ("").

-atau-

DeliveryMethod properti diatur ke Network dan Port adalah nol, angka negatif, atau lebih besar dari 65.535.

Obyek ini telah dibuang.

Koneksi ke server SMTP gagal.

-atau-

Autentikasi gagal.

-atau-

Waktu operasi habis.

-atau-

EnableSsl diatur ke true tetapi DeliveryMethod properti diatur ke SpecifiedPickupDirectory atau PickupDirectoryFromIis.

-atau-

EnableSsl diatur ke true, tetapi server email SMTP tidak mengiklankan STARTTLS sebagai respons terhadap perintah EHLO.

-atau-

message tidak dapat dikirimkan ke satu atau beberapa penerima di To, , CCatau Bcc.

message tidak dapat dikirimkan ke salah satu penerima di To, , CCatau Bcc.

message tidak dapat dikirimkan ke dua atau lebih penerima di To, , CCatau Bcc.

Contoh

Contoh kode berikut menunjukkan pemanggilan metode ini.

#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

Keterangan

Untuk menerima pemberitahuan ketika email telah dikirim atau operasi telah dibatalkan, tambahkan penanganan aktivitas ke SendCompleted acara. Anda dapat membatalkan SendAsync operasi dengan memanggil SendAsyncCancel metode .

Setelah memanggil SendAsync, Anda harus menunggu transmisi email selesai sebelum mencoba mengirim pesan email lain menggunakan Send atau SendAsync.

Sebelum memanggil metode ini, Host dan Port harus diatur melalui file konfigurasi dengan mengatur properti yang relevan, atau dengan meneruskan informasi ini ke SmtpClient(String, Int32) konstruktor.

Jika host SMTP memerlukan kredensial, Anda harus mengaturnya sebelum memanggil metode ini. Untuk menentukan kredensial, gunakan UseDefaultCredentials properti atau Credentials .

Jika Anda menerima SmtpException pengecualian, periksa StatusCode properti untuk menemukan alasan operasi gagal. juga SmtpException dapat berisi pengecualian dalam yang menunjukkan alasan operasi gagal.

Saat mengirim email menggunakan SendAsync ke beberapa penerima, jika server SMTP menerima beberapa penerima sebagai valid dan menolak orang lain, SmtpException dilemparkan dengan NullReferenceException untuk pengecualian dalam. Jika ini terjadi, SendAsync gagal mengirim email ke salah satu penerima.

Aplikasi Anda dapat mendeteksi kesalahan validasi sertifikat server dengan memeriksa properti yang Error diteruskan ke SendCompletedEventHandler delegasi.

Properti Timeout tidak berpengaruh pada SendAsync panggilan.

Untuk mengirim email dan memblokir saat dikirimkan ke server SMTP, gunakan salah Send satu metode.

Catatan

EnableSsl Jika properti diatur ke true, dan server email SMTP tidak mengiklankan STARTTLS sebagai respons terhadap perintah EHLO, maka panggilan ke Send metode atau SendAsync akan melempar SmtpException.

Berlaku untuk

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

Sumber:
SmtpClient.cs
Sumber:
SmtpClient.cs
Sumber:
SmtpClient.cs

Mengirim pesan email ke server SMTP untuk pengiriman. Pengirim pesan, penerima, subjek, dan isi pesan ditentukan menggunakan String objek. Metode ini tidak memblokir utas panggilan dan memungkinkan pemanggil untuk meneruskan objek ke metode yang dipanggil ketika operasi selesai.

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)

Parameter

from
String

yang String berisi informasi alamat pengirim pesan.

recipients
String

String yang berisi alamat tempat pesan dikirim.

subject
String

String yang berisi baris subjek untuk pesan.

body
String

yang String berisi isi pesan.

userToken
Object

Objek yang ditentukan pengguna yang diteruskan ke metode yang dipanggil saat operasi asinkron selesai.

Pengecualian

fromadalah null.

-atau-

recipientadalah null.

fromadalah Empty.

-atau-

recipientadalah Empty.

Ini SmtpClient memiliki panggilan yang SendAsync sedang berlangsung.

-atau-

DeliveryMethod properti diatur ke Network dan Host adalah null.

-atau-

DeliveryMethod properti diatur ke Network dan Host sama dengan string kosong ("").

-atau-

DeliveryMethod properti diatur ke Network dan Port adalah nol, angka negatif, atau lebih besar dari 65.535.

Obyek ini telah dibuang.

Koneksi ke server SMTP gagal.

-atau-

Autentikasi gagal.

-atau-

Waktu operasi habis.

-atau-

EnableSsl diatur ke true tetapi DeliveryMethod properti diatur ke SpecifiedPickupDirectory atau PickupDirectoryFromIis.

-atau-

EnableSsl diatur ke true, tetapi server email SMTP tidak mengiklankan STARTTLS sebagai respons terhadap perintah EHLO.

-atau-

Pesan tidak dapat dikirimkan ke satu atau beberapa penerima di recipients.

message tidak dapat dikirimkan ke salah satu penerima di To, , CCatau Bcc.

message tidak dapat dikirimkan ke dua atau lebih penerima di To, , CCatau Bcc.

Keterangan

Untuk menerima pemberitahuan ketika email telah dikirim atau operasi telah dibatalkan, tambahkan penanganan aktivitas ke SendCompleted acara. Anda dapat membatalkan SendAsync operasi dengan memanggil SendAsyncCancel metode .

Setelah memanggil SendAsync, Anda harus menunggu transmisi email selesai sebelum mencoba mengirim pesan email lain menggunakan Send atau SendAsync.

Sebelum memanggil metode ini, Host properti dan Port harus diatur baik melalui file konfigurasi atau dengan mengatur properti atau meneruskan informasi ini ke SmtpClient(String, Int32) konstruktor.

Jika host SMTP memerlukan kredensial, Anda harus mengaturnya sebelum memanggil metode ini. Untuk menentukan kredensial, gunakan UseDefaultCredentials properti atau Credentials .

Jika Anda menerima SmtpException pengecualian, periksa StatusCode properti untuk menemukan alasan operasi gagal. SmtpException juga dapat berisi pengecualian dalam yang menunjukkan alasan operasi gagal.

Saat mengirim email menggunakan SendAsync ke beberapa penerima, jika server SMTP menerima beberapa penerima sebagai valid dan menolak yang lain, SmtpException dilemparkan dengan NullReferenceException untuk pengecualian dalam. Jika ini terjadi, SendAsync gagal mengirim email ke salah satu penerima.

Aplikasi Anda dapat mendeteksi kesalahan validasi sertifikat server dengan memeriksa properti yang Error diteruskan ke SendCompletedEventHandler delegasi.

Properti Timeout tidak berpengaruh pada SendAsync panggilan.

Untuk mengirim email dan memblokir saat dikirimkan ke server SMTP, gunakan salah Send satu metode.

Catatan

EnableSsl Jika properti diatur ke true, dan server email SMTP tidak mengiklankan STARTTLS sebagai respons terhadap perintah EHLO, maka panggilan ke Send metode atau SendAsync akan melempar SmtpException.

Berlaku untuk