SmtpClient.SendAsync 方法

定義

傳送電子郵件訊息。 這些方法不會封鎖呼叫執行緒。

多載

SendAsync(MailMessage, Object)

傳送指定的電子郵件訊息給 SMTP 伺服器進行傳遞。 這個方法不會封鎖呼叫執行緒,而且允許呼叫端將物件傳遞給作業完成時所叫用 (Invoke) 的方法。

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

傳送電子郵件訊息給 SMTP 伺服器進行傳遞。 訊息寄件者、收件者、主旨和訊息主體是使用 String 物件來指定。 這個方法不會封鎖呼叫執行緒,而且允許呼叫端將物件傳遞給作業完成時所叫用 (Invoke) 的方法。

SendAsync(MailMessage, Object)

來源:
SmtpClient.cs
來源:
SmtpClient.cs
來源:
SmtpClient.cs

傳送指定的電子郵件訊息給 SMTP 伺服器進行傳遞。 這個方法不會封鎖呼叫執行緒,而且允許呼叫端將物件傳遞給作業完成時所叫用 (Invoke) 的方法。

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)

參數

message
MailMessage

MailMessage,包含要傳送的訊息。

userToken
Object

使用者定義的物件,這個物件會在非同步作業完成時傳遞至叫用的方法。

例外狀況

messagenull

-或-

Fromnull

SmtpClient 有另一個已在進行中的傳送作業。

-或-

ToCCBcc 屬性中沒有指定任何收件者。

-或-

DeliveryMethod 屬性設定為 Network,且 Hostnull

-或-

DeliveryMethod 屬性設為 Network,且 Host 等於空字串 ("")。

-或-

DeliveryMethod 屬性設定為 Network ,而且 Port 為零、負數或大於 65,535。

這個物件已經過處置。

與 SMTP 伺服器的連接失敗。

-或-

驗證失敗。

-或-

作業逾時。

-或-

EnableSsl 設定為 true,但 DeliveryMethod 屬性設定為 SpecifiedPickupDirectoryPickupDirectoryFromIis

-或-

EnableSsl 設為 true, 不過 SMTP 郵件伺服器並未在對 EHLO 命令的回應中通告 STARTTLS。

-或-

無法將 message 傳遞給 ToCCBcc 中的一個或多個收件者。

無法將 message 傳遞給 ToCCBcc 中的一個收件者。

無法將 message 傳遞給 ToCCBcc 中的兩個或多個收件者。

範例

下列程式碼範例示範如何呼叫這個方法。

#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

備註

若要在傳送電子郵件或取消作業時收到通知,請將事件處理常式新增至 SendCompleted 事件。 您可以呼叫 SendAsyncCancel 方法來取消 SendAsync 作業。

呼叫 SendAsync 之後,您必須先等候電子郵件傳輸完成,才能嘗試使用 SendSendAsync 傳送另一封電子郵件訊息。

在呼叫這個方法之前, HostPort 必須透過組態檔來設定相關屬性,或將這項資訊傳遞至 SmtpClient(String, Int32) 建構函式。

如果 SMTP 主機需要認證,您必須先設定認證,才能呼叫此方法。 若要指定認證,請使用 UseDefaultCredentialsCredentials 屬性。

如果您收到 SmtpException 例外狀況,請檢查 StatusCode 屬性以找出作業失敗的原因。 SmtpException也可以包含內部例外狀況,指出作業失敗的原因。

使用 傳送電子郵件 SendAsync 給多個收件者時,如果 SMTP 伺服器接受某些收件者為有效,並拒絕其他收件者,則會擲回 , SmtpExceptionNullReferenceException 針對內部例外狀況擲回 。 如果發生這種情況, SendAsync 則無法傳送電子郵件給任何收件者。

您的應用程式可以藉由檢查 Error 傳入委派的 SendCompletedEventHandler 屬性,來偵測伺服器憑證驗證錯誤。

屬性 Timeout 對呼叫沒有任何影響 SendAsync

若要在傳送至 SMTP 伺服器時傳送郵件並封鎖,請使用其中 Send 一種方法。

注意

EnableSsl如果 屬性設定為 true ,且 SMTP 郵件伺服器不會在回應 EHLO 命令中公告 STARTTLS,則 對 或 SendAsync 方法的呼叫 Send 會擲回 SmtpException

適用於

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

來源:
SmtpClient.cs
來源:
SmtpClient.cs
來源:
SmtpClient.cs

傳送電子郵件訊息給 SMTP 伺服器進行傳遞。 訊息寄件者、收件者、主旨和訊息主體是使用 String 物件來指定。 這個方法不會封鎖呼叫執行緒,而且允許呼叫端將物件傳遞給作業完成時所叫用 (Invoke) 的方法。

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)

參數

from
String

String,包含訊息寄件者的地址資訊。

recipients
String

String,包含訊息要傳送到的地址。

subject
String

String,包含訊息的主旨行。

body
String

String,包含訊息主體。

userToken
Object

使用者定義的物件,這個物件會在非同步作業完成時傳遞至叫用的方法。

例外狀況

fromnull

-或-

recipientnull

fromEmpty

-或-

recipientEmpty

這個 SmtpClient 有正在進行中的 SendAsync 呼叫。

-或-

DeliveryMethod 屬性設定為 Network,且 Hostnull

-或-

DeliveryMethod 屬性設為 Network,且 Host 等於空字串 ("")。

-或-

DeliveryMethod 屬性設定為 Network ,而且 Port 為零、負數或大於 65,535。

這個物件已經過處置。

與 SMTP 伺服器的連接失敗。

-或-

驗證失敗。

-或-

作業逾時。

-或-

EnableSsl 設定為 true,但 DeliveryMethod 屬性設定為 SpecifiedPickupDirectoryPickupDirectoryFromIis

-或-

EnableSsl 設為 true, 不過 SMTP 郵件伺服器並未在對 EHLO 命令的回應中通告 STARTTLS。

-或-

無法將訊息傳遞給 recipients 中的一個或多個收件者。

無法將 message 傳遞給 ToCCBcc 中的一個收件者。

無法將 message 傳遞給 ToCCBcc 中的兩個或多個收件者。

備註

若要在傳送電子郵件或取消作業時收到通知,請將事件處理常式新增至 SendCompleted 事件。 您可以呼叫 SendAsyncCancel 方法來取消 SendAsync 作業。

呼叫 SendAsync 之後,您必須先等候電子郵件傳輸完成,才能嘗試使用 SendSendAsync 傳送另一封電子郵件訊息。

在呼叫此方法之前, Host 必須透過組態檔或設定屬性,或將此資訊傳遞至 SmtpClient(String, Int32) 建構函式來設定 和 Port 屬性。

如果 SMTP 主機需要認證,您必須先設定認證,才能呼叫此方法。 若要指定認證,請使用 UseDefaultCredentialsCredentials 屬性。

如果您收到 SmtpException 例外狀況,請檢查 StatusCode 屬性以找出作業失敗的原因。 SmtpException也可以包含內部例外狀況,指出作業失敗的原因。

當使用 SendAsync 傳送電子郵件給多個收件者時,如果 SMTP 伺服器接受某些收件者有效,並拒絕其他收件者, SmtpException 則會擲回 ,並 NullReferenceException 針對內部例外狀況擲回 。 如果發生這種情況, SendAsync 則無法傳送電子郵件給任何收件者。

您的應用程式可以藉由檢查 Error 傳入委派的屬性 SendCompletedEventHandler 來偵測伺服器憑證驗證錯誤。

屬性 Timeout 對呼叫沒有任何影響 SendAsync

若要在傳送至 SMTP 伺服器時傳送郵件並封鎖,請使用其中 Send 一種方法。

注意

EnableSsl如果 屬性設定 true 為 ,且 SMTP 郵件伺服器不會在回應 EHLO 命令中公告 STARTTLS,則 Send 呼叫 或 SendAsync 方法會擲回 SmtpException

適用於