SmtpClient.SendAsync SmtpClient.SendAsync SmtpClient.SendAsync SmtpClient.SendAsync Method

定義

傳送電子郵件訊息。Sends an email message. 這些方法不會封鎖呼叫執行緒。These methods do not block the calling thread.

多載

SendAsync(MailMessage, Object) SendAsync(MailMessage, Object) SendAsync(MailMessage, Object) SendAsync(MailMessage, Object)

傳送指定的電子郵件訊息給 SMTP 伺服器進行傳遞。Sends the specified email message to an SMTP server for delivery. 這個方法不會封鎖呼叫執行緒,而且允許呼叫端將物件傳遞給作業完成時所叫用 (Invoke) 的方法。This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes.

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

傳送電子郵件訊息給 SMTP 伺服器進行傳遞。Sends an email message to an SMTP server for delivery. 訊息寄件者、收件者、主旨和訊息主體是使用 String 物件來指定。The message sender, recipients, subject, and message body are specified using String objects. 這個方法不會封鎖呼叫執行緒,而且允許呼叫端將物件傳遞給作業完成時所叫用 (Invoke) 的方法。This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes.

SendAsync(MailMessage, Object) SendAsync(MailMessage, Object) SendAsync(MailMessage, Object) SendAsync(MailMessage, Object)

傳送指定的電子郵件訊息給 SMTP 伺服器進行傳遞。Sends the specified email message to an SMTP server for delivery. 這個方法不會封鎖呼叫執行緒,而且允許呼叫端將物件傳遞給作業完成時所叫用 (Invoke) 的方法。This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes.

public:
 void SendAsync(System::Net::Mail::MailMessage ^ message, System::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 MailMessage MailMessage

MailMessage,包含要傳送的訊息。A MailMessage that contains the message to send.

userToken
Object Object Object Object

使用者定義的物件,這個物件會在非同步作業完成時傳遞至叫用的方法。A user-defined object that is passed to the method invoked when the asynchronous operation completes.

例外狀況

messagenullmessage is null.

-或--or- FromnullFrom is null.

這個 SmtpClient 有正在進行中的 SendAsync 呼叫。This SmtpClient has a SendAsync call in progress.

-或--or- ToCCBcc 屬性中沒有指定任何收件者。There are no recipients specified in To, CC, and Bcc properties.

-或--or- DeliveryMethod 屬性設定為 Network,且 HostnullDeliveryMethod property is set to Network and Host is null.

-或--or- DeliveryMethod 屬性設為 Network,且 Host 等於空字串 ("")。DeliveryMethod property is set to Network and Host is equal to the empty string ("").

-或--or- DeliveryMethod 屬性設定為 Network ,而且 Port 為零、負數或大於 65,535。DeliveryMethod property is set to Network and Port is zero, a negative number, or greater than 65,535.

這個物件已經過處置。This object has been disposed.

與 SMTP 伺服器的連接失敗。The connection to the SMTP server failed.

-或--or- 驗證失敗。Authentication failed.

-或--or- 作業逾時。The operation timed out. -或--or- EnableSsl 設定為 true,但 DeliveryMethod 屬性設定為 SpecifiedPickupDirectoryPickupDirectoryFromIisEnableSsl is set to true but the DeliveryMethod property is set to SpecifiedPickupDirectory or PickupDirectoryFromIis.

-或--or- EnableSsl 設為 true, 不過 SMTP 郵件伺服器並未在對 EHLO 命令的回應中通告 STARTTLS。EnableSsl is set to true, but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command.

-或--or- 無法將 message 傳遞給 ToCCBcc 中的一個或多個收件者。The message could not be delivered to one or more of the recipients in To, CC, or Bcc.

範例

下列程式碼範例將示範如何呼叫這個方法。The following code example demonstrates calling this method.

#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事件。To receive notification when the email has been sent or the operation has been canceled, add an event handler to the SendCompleted event. 您可以藉由SendAsync SendAsyncCancel呼叫方法來取消作業。You can cancel a SendAsync operation by calling the SendAsyncCancel method.

呼叫SendAsync之後,您必須等候電子郵件傳輸完成,然後再嘗試使用SendSendAsync傳送另一封電子郵件訊息。After calling SendAsync, you must wait for the email transmission to complete before attempting to send another email message using Send or SendAsync.

在呼叫這個方法之前, HostPort必須透過設定相關的屬性,或將此資訊SmtpClient(String, Int32)傳遞至此函式,來設定和的設定檔案。Before calling this method, the Host and Port must be set through the configuration files by setting the relevant properties, or by passing this information into the SmtpClient(String, Int32) constructor.

如果 SMTP 主機需要認證,您必須在呼叫此方法之前設定它們。If the SMTP host requires credentials, you must set them before calling this method. 若要指定認證,請UseDefaultCredentials使用Credentials或屬性。To specify credentials, use the UseDefaultCredentials or Credentials properties.

如果您收到SmtpException例外狀況,請StatusCode檢查屬性,以找出作業失敗的原因。If you receive an SmtpException exception, check the StatusCode property to find the reason the operation failed. SmtpException可以包含內部例外狀況,指出作業失敗的原因。The SmtpException can also contain an inner exception that indicates the reason the operation failed.

使用SendAsync傳送電子郵件給多個收件者時,如果 SMTP 伺服器接受某些收件者有效並SmtpException拒絕其他收件NullReferenceException者,則會擲回,並提供內部例外狀況的。When sending email using SendAsync to multiple recipients, if the SMTP server accepts some recipients as valid and rejects others, a SmtpException is thrown with a NullReferenceException for the inner exception. 如果發生這種SendAsync情況,就無法傳送電子郵件給任何收件者。If this occurs, SendAsync fails to send email to any of the recipients.

您的應用程式可以藉由檢查傳入Error SendCompletedEventHandler委派的屬性來偵測伺服器憑證驗證錯誤。Your application can detect a server certificate validation error by examining the Error property passed into the SendCompletedEventHandler delegate.

屬性對SendAsync呼叫不會有任何影響。 TimeoutThe Timeout property does not have any effect on a SendAsync call.

若要在傳送郵件並封鎖到 SMTP 伺服器時傳送它,請使用其中一Send種方法。To send mail and block while it is transmitted to the SMTP server, use one of the Send methods.

注意

true Send SendAsync如果屬性設定為,而 SMTP 郵件伺服器並未在對 EHLO 命令的回應中公告 STARTTLS,則呼叫或方法將會擲SmtpException回。 EnableSslIf the EnableSsl property is set to true, and the SMTP mail server does not advertise STARTTLS in the response to the EHLO command, then a call to the Send or SendAsync methods will throw an SmtpException.

安全性

SmtpPermission
連接到 SMTP 伺服器。to connect to the SMTP server. 相關聯的列舉:ConnectAssociated enumeration: Connect

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

傳送電子郵件訊息給 SMTP 伺服器進行傳遞。Sends an email message to an SMTP server for delivery. 訊息寄件者、收件者、主旨和訊息主體是使用 String 物件來指定。The message sender, recipients, subject, and message body are specified using String objects. 這個方法不會封鎖呼叫執行緒,而且允許呼叫端將物件傳遞給作業完成時所叫用 (Invoke) 的方法。This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes.

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

參數

from
String String String String

String,包含訊息寄件者的地址資訊。A String that contains the address information of the message sender.

recipients
String String String String

String,包含訊息要傳送到的地址。A String that contains the address that the message is sent to.

subject
String String String String

String,包含訊息的主旨行。A String that contains the subject line for the message.

body
String String String String

String,包含訊息主體。A String that contains the message body.

userToken
Object Object Object Object

使用者定義的物件,這個物件會在非同步作業完成時傳遞至叫用的方法。A user-defined object that is passed to the method invoked when the asynchronous operation completes.

例外狀況

fromnullfrom is null.

-或--or- recipientnullrecipient is null.

fromEmptyfrom is Empty.

-或--or- recipientEmptyrecipient is Empty.

這個 SmtpClient 有正在進行中的 SendAsync 呼叫。This SmtpClient has a SendAsync call in progress.

-或--or- DeliveryMethod 屬性設定為 Network,且 HostnullDeliveryMethod property is set to Network and Host is null.

-或--or- DeliveryMethod 屬性設為 Network,且 Host 等於空字串 ("")。DeliveryMethod property is set to Network and Host is equal to the empty string ("").

-或--or- DeliveryMethod 屬性設定為 Network ,而且 Port 為零、負數或大於 65,535。DeliveryMethod property is set to Network and Port is zero, a negative number, or greater than 65,535.

這個物件已經過處置。This object has been disposed.

與 SMTP 伺服器的連接失敗。The connection to the SMTP server failed.

-或--or- 驗證失敗。Authentication failed.

-或--or- 作業逾時。The operation timed out. -或--or- EnableSsl 設定為 true,但 DeliveryMethod 屬性設定為 SpecifiedPickupDirectoryPickupDirectoryFromIisEnableSsl is set to true but the DeliveryMethod property is set to SpecifiedPickupDirectory or PickupDirectoryFromIis.

-或--or- EnableSsl 設為 true, 不過 SMTP 郵件伺服器並未在對 EHLO 命令的回應中通告 STARTTLS。EnableSsl is set to true, but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command.

-或--or- 無法將訊息傳遞給 recipients 中的一個或多個收件者。The message could not be delivered to one or more of the recipients in recipients.

備註

若要在傳送電子郵件或取消作業時收到通知,請將事件處理常式新增至SendCompleted事件。To receive notification when the email has been sent or the operation has been canceled, add an event handler to the SendCompleted event. 您可以藉由SendAsync SendAsyncCancel呼叫方法來取消作業。You can cancel a SendAsync operation by calling the SendAsyncCancel method.

呼叫SendAsync之後,您必須等候電子郵件傳輸完成,然後再嘗試使用SendSendAsync傳送另一封電子郵件訊息。After calling SendAsync, you must wait for the email transmission to complete before attempting to send another email message using Send or SendAsync.

Host呼叫這個方法之前,必須Port透過設定檔或設定屬性,或將這項資訊SmtpClient(String, Int32)傳遞至函式,來設定和屬性。Before calling this method, the Host and Port properties must be set either through the configuration files or by setting the properties or passing this information into the SmtpClient(String, Int32) constructor.

如果 SMTP 主機需要認證,您必須在呼叫此方法之前設定它們。If the SMTP host requires credentials, you must set them before calling this method. 若要指定認證,請UseDefaultCredentials使用Credentials或屬性。To specify credentials, use the UseDefaultCredentials or Credentials property.

如果您收到SmtpException例外狀況,請StatusCode檢查屬性,以找出作業失敗的原因。If you receive an SmtpException exception, check the StatusCode property to find the reason the operation failed. SmtpException可以包含內部例外狀況,指出作業失敗的原因。The SmtpException can also contain an inner exception that indicates the reason the operation failed.

使用SendAsync傳送電子郵件給多個收件者時,如果 SMTP 伺服器接受某些收件者有效並SmtpException拒絕其他收件NullReferenceException者,則會擲回,並提供內部例外狀況的。When sending email using SendAsync to multiple recipients, if the SMTP server accepts some recipients as valid and rejects others, a SmtpException is thrown with a NullReferenceException for the inner exception. 如果發生這種SendAsync情況,就無法傳送電子郵件給任何收件者。If this occurs, SendAsync fails to send email to any of the recipients.

您的應用程式可以藉由檢查傳入Error SendCompletedEventHandler委派的屬性來偵測伺服器憑證驗證錯誤。Your application can detect a server certificate validation error by examining the Error property passed into the SendCompletedEventHandler delegate.

屬性對SendAsync呼叫不會有任何影響。 TimeoutThe Timeout property does not have any effect on a SendAsync call.

若要在傳送郵件並封鎖到 SMTP 伺服器時傳送它,請使用其中一Send種方法。To send mail and block while it is transmitted to the SMTP server, use one of the Send methods.

注意

true Send SendAsync如果屬性設定為,而 SMTP 郵件伺服器並未在對 EHLO 命令的回應中公告 STARTTLS,則呼叫或方法將會擲SmtpException回。 EnableSslIf the EnableSsl property is set to true, and the SMTP mail server does not advertise STARTTLS in the response to the EHLO command, then a call to the Send or SendAsync methods will throw an SmtpException.

安全性

SmtpPermission
連接到 SMTP 伺服器。To connect to the SMTP server. 相關聯的列舉:ConnectAssociated enumeration: Connect

適用於