語言

SmtpClient.SendAsync 方法

定義

傳送電子郵件訊息。 這些方法不會封鎖呼叫線程。

多載

名稱 Description
SendAsync(MailMessage, Object)

將指定的電子郵件發送至 SMTP 伺服器進行投遞。 此方法不會阻擋呼叫執行緒,並允許呼叫者將物件傳給操作完成時所呼叫的方法。

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

發送電子郵件至SMTP伺服器進行投遞。 訊息發送者、收件人、主旨與訊息正文皆以 String 物件來指定。 此方法不會阻擋呼叫執行緒,並允許呼叫者將物件傳給操作完成時所呼叫的方法。

SendAsync(MailMessage, Object)

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

將指定的電子郵件發送至 SMTP 伺服器進行投遞。 此方法不會阻擋呼叫執行緒,並允許呼叫者將物件傳給操作完成時所呼叫的方法。

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 A 包含要傳送的訊息。

userToken
Object

使用者定義對象,傳遞至異步操作完成時叫用的方法。

例外狀況

message 是 null。

-或-

From 是 null。

這 SmtpClient 其中還有另一個傳送操作正在進行中。

-或-

在 、 To和 CC 屬性中Bcc未指定接收者。

-或-

DeliveryMethod 屬性設為 Network ,且 Host 為 null。

-或-

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

-或-

DeliveryMethod 性質設為 Network ,且 Port 為零,為負數,或大於 65,535。

此物已被處理。

連接到 SMTP 伺服器時失敗了。

-或-

驗證失敗。

-或-

作業逾時。

-或-

EnableSsl 設定為 , true 但 DeliveryMethod 屬性設定為 SpecifiedPickupDirectory 或 PickupDirectoryFromIis。

-或-

EnableSsl 設定為 , true, 但 SMTP 郵件伺服器在回應 EHLO 指令時並未宣告 STARTTLS。

-或-

無法message送達給 、 、 To或 CC中的一位或多位收件人Bcc。

無法message送達 、 To、 或 CC的收件人Bcc。

無法message送達兩位或以上的ToCCBcc收件人。

範例

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


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

備註

若想收到郵件已發送或操作取消的通知,請在事件中新增事件處理 SendCompleted 程式。 你可以透過呼叫該SendAsync方法來取消操作SendAsyncCancel。

撥打 SendAsync後,您必須等待電子郵件傳送完成後,再嘗試使用 Send 或 SendAsync發送另一封電子郵件。

在呼叫此方法之前,Host必須透過設定檔設定相關屬性,或將這些資訊傳入Port建構子,先設定 andSmtpClient(String, Int32)。

如果 SMTP 主機需要憑證,你必須先設定好憑證,然後才呼叫這個方法。 要指定憑證,請使用 UseDefaultCredentials or Credentials 屬性。

如果收到 SmtpException 例外,請檢查該 StatusCode 屬性以找出操作失敗的原因。 也可以 SmtpException 包含一個內部例外,指示操作失敗的原因。

當向多個收件人發送電子郵件 SendAsync 時,如果 SMTP 伺服器接受部分收件人為有效且拒絕其他,則會拋出 a SmtpException 並產生 NullReferenceException 內部例外。 若發生此情況,則 SendAsync 無法向任何收件人發送電子郵件。

您的應用程式可以透過檢查 Error 傳入 SendCompletedEventHandler 代理的屬性來偵測伺服器憑證驗證錯誤。

該 Timeout 屬性對通話 SendAsync 無影響。

若要發送郵件並在郵件傳送至SMTP伺服器時封鎖,請使用以下 Send 方法之一。

Note

若 EnableSsl 屬性設為 true,且 SMTP 郵件伺服器在回應 EHLO 指令時未宣告 STARTTLS,則呼叫 Send or SendAsync 方法會拋出 SmtpException。

適用於

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

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

發送電子郵件至SMTP伺服器進行投遞。 訊息發送者、收件人、主旨與訊息正文皆以 String 物件來指定。 此方法不會阻擋呼叫執行緒,並允許呼叫者將物件傳給操作完成時所呼叫的方法。

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 A 包含訊息發送者的地址資訊。

recipients
String

A String 包含訊息發送地址。

subject
String

String A,其中包含訊息主旨。

body
String

String A 包含訊息主體。

userToken
Object

使用者定義對象,傳遞至異步操作完成時叫用的方法。

例外狀況

from 是 null。

-或-

recipients 是 null。

from 是 Empty。

-或-

recipients 是 Empty。

這 SmtpClient 通 SendAsync 電話正在進行中。

-或-

DeliveryMethod 屬性設為 Network ,且 Host 為 null。

-或-

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

-或-

DeliveryMethod 性質設為 Network ,且 Port 為零,為負數,或大於 65,535。

此物已被處理。

連接到 SMTP 伺服器時失敗了。

-或-

驗證失敗。

-或-

作業逾時。

-或-

EnableSsl 設定為 , true 但 DeliveryMethod 屬性設定為 SpecifiedPickupDirectory 或 PickupDirectoryFromIis。

-或-

EnableSsl 設定為 , true, 但 SMTP 郵件伺服器在回應 EHLO 指令時並未宣告 STARTTLS。

-或-

訊息無法傳送給 。recipients

訊息無法送達 、 To、 或 CC的收件人Bcc。

訊息無法同時送達兩位或以上的To收件人。 CCBcc

備註

若想收到郵件已發送或操作取消的通知,請在事件中新增事件處理 SendCompleted 程式。 你可以透過呼叫該SendAsync方法來取消操作SendAsyncCancel。

撥打 SendAsync後,您必須等待電子郵件傳送完成後,再嘗試使用 Send 或 SendAsync發送另一封電子郵件。

在呼叫此方法之前, Host 必須透過設定檔設定 and Port 屬性,或透過設定屬性或將這些資訊傳入 SmtpClient(String, Int32) 建構子來設定。

如果 SMTP 主機需要憑證,你必須先設定好憑證,然後才呼叫這個方法。 要指定憑證,請使用或UseDefaultCredentialsCredentials屬性。

如果收到 SmtpException 例外,請檢查該 StatusCode 屬性以找出操作失敗的原因。 也可以 SmtpException 包含一個內部例外,指示操作失敗的原因。

當向多個收件人發送電子郵件 SendAsync 時,如果 SMTP 伺服器接受部分收件人為有效且拒絕其他,則會拋出 a SmtpException 並產生 NullReferenceException 內部例外。 若發生此情況,則 SendAsync 無法向任何收件人發送電子郵件。

您的應用程式可以透過檢查 Error 傳入 SendCompletedEventHandler 代理的屬性來偵測伺服器憑證驗證錯誤。

該 Timeout 屬性對通話 SendAsync 無影響。

若要發送郵件並在郵件傳送至SMTP伺服器時封鎖,請使用以下 Send 方法之一。

Note

若 EnableSsl 屬性設為 true,且 SMTP 郵件伺服器在回應 EHLO 指令時未宣告 STARTTLS,則呼叫 Send or SendAsync 方法會拋出 SmtpException。

適用於