SmtpClient.SendAsync 方法

定义

发送电子邮件。 这些方法不阻止调用线程。

重载

SendAsync(MailMessage, Object)

将指定的电子邮件发送到 SMTP 服务器以便传递。 此方法不阻止调用线程,并允许调用方将对象传递给操作完成后调用的方法。

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

将电子邮件发送到 SMTP 服务器以便传递。 使用 String 对象指定邮件的发件人、收件人、主题和邮件正文。 此方法不阻止调用线程,并允许调用方将对象传递给操作完成后调用的方法。

SendAsync(MailMessage, Object)

Source:
SmtpClient.cs
Source:
SmtpClient.cs
Source:
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

userToken
Object

一个用户定义对象,此对象将传递给完成异步操作后所调用的方法。

例外

message 上声明的默认值为 null

From 上声明的默认值为 null

SmtpClient 还有另一个正在执行的发送操作。

- 或 -

ToCCBcc 属性中没有指定的收件人。

- 或 -

DeliveryMethod 属性设置为 Network,且 Hostnull

- 或 -

DeliveryMethod 属性设置为 NetworkHost 等于空字符串 ("")。

- 或 -

DeliveryMethod 属性被设为 NetworkPort 为零、负数或大于 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发送另一封电子邮件。

在调用此方法之前,Host必须通过配置文件设置相关属性或将此信息传递到构造函数中SmtpClient(String, Int32)来设置 和Port

如果 SMTP 主机需要凭据,则必须在调用此方法之前对其进行设置。 若要指定凭据,请使用 UseDefaultCredentialsCredentials 属性。

如果收到SmtpException异常,检查 StatusCode 属性来查找操作失败的原因。 还可以 SmtpException 包含指示操作失败原因的内部异常。

使用 SendAsync 向多个收件人发送电子邮件时,如果 SMTP 服务器接受一些有效收件人并拒绝其他收件人, SmtpException 则会引发 包含 NullReferenceException 内部异常的 。 如果发生这种情况, SendAsync 则无法向任何收件人发送电子邮件。

应用程序可以通过检查传递到SendCompletedEventHandler委托中的 Error 属性来检测服务器证书验证错误。

属性 Timeout 对调用没有任何影响 SendAsync

若要在邮件传输到 SMTP 服务器时发送邮件并阻止邮件,请使用方法之 Send 一。

注意

EnableSsl如果 属性设置为 true,并且 SMTP 邮件服务器在响应 EHLO 命令时不播发 STARTTLS,则对 SendSendAsync 方法的调用将引发 SmtpException

适用于

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

Source:
SmtpClient.cs
Source:
SmtpClient.cs
Source:
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

recipients
String

包含邮件收件人的地址的 String

subject
String

一个包含邮件主题行的 String

body
String

一个包含邮件正文的 String

userToken
Object

一个用户定义对象,此对象将传递给完成异步操作后所调用的方法。

例外

from 上声明的默认值为 null

recipient 上声明的默认值为 null

from 上声明的默认值为 Empty

recipientEmpty

SmtpClient 有一个 SendAsync 调用正在进行。

- 或 -

DeliveryMethod 属性设置为 Network,且 Hostnull

- 或 -

DeliveryMethod 属性设置为 NetworkHost 等于空字符串 ("")。

- 或 -

DeliveryMethod 属性被设为 NetworkPort 为零、负数或大于 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 将无法向任何收件人发送电子邮件。

应用程序可以通过检查传入SendCompletedEventHandler委托的属性Error来检测服务器证书验证错误。

属性 Timeout 对调用没有任何影响 SendAsync

若要在邮件传输到 SMTP 服务器时发送邮件并阻止邮件,请使用 方法之 Send 一。

注意

如果 属性 EnableSsl 设置为 true,并且 SMTP 邮件服务器在响应 EHLO 命令时不播发 STARTTLS,则对 SendSendAsync 方法的调用将引发 SmtpException

适用于