语言

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
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

包含要发送的消息的 A MailMessage 。

userToken
Object

在异步操作完成时传递给调用的方法的用户定义对象。

例外

message 是 null。

-或-

From 是 null。

此操作 SmtpClient 还有另一个正在进行中的发送操作。

-或-

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

-或-

DeliveryMethod 属性设置为 Network 和 Host is null。

-或-

DeliveryMethod 属性设置为 Network 空字符串( Host “”)

-或-

DeliveryMethod 属性设置为 Network 零, Port 负数或大于 65,535。

此对象已被释放。

与 SMTP 服务器的连接失败。

-或-

身份验证失败。

-或-

操作超时。

-或-

EnableSsl 设置为 true ,但属性 DeliveryMethod 设置为 SpecifiedPickupDirectory 或 PickupDirectoryFromIis。

-或-

EnableSsl 设置为 true, SMTP 邮件服务器未在响应 EHLO 命令时播发 STARTTLS。

-或-

无法将邮件message传递到一个或多个收件人,ToCC或者Bcc。

无法将邮件 message 传递到其中 To一个收件人, CC或者 Bcc。

message无法向两个或更多收件人To送达,CC或者Bcc。

示例

下面的代码示例演示如何调用此方法。


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构造函数来设置配置文件SmtpClient(String, Int32)。

如果 SMTP 主机需要凭据,则必须在调用此方法之前设置凭据。 若要指定凭据,请使用 UseDefaultCredentials 或 Credentials 属性。

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

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

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

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

若要在将邮件传输到 SMTP 服务器时发送邮件和阻止,请使用其中 Send 一种方法。

注释

如果属性 EnableSsl 设置为 true,并且 SMTP 邮件服务器不会在响应 EHLO 命令时播发 STARTTLS,则调用 Send 或 SendAsync 方法将引发一个 SmtpException。

适用于

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

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

包含消息发送到的地址的 A String 。

subject
String

包含邮件的主题行的 A String 。

body
String

包含消息正文的 A String 。

userToken
Object

在异步操作完成时传递给调用的方法的用户定义对象。

例外

from 是 null。

-或-

recipients 是 null。

from 是 Empty。

-或-

recipients 是 Empty。

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

-或-

DeliveryMethod 属性设置为 Network 和 Host is null。

-或-

DeliveryMethod 属性设置为 Network 空字符串( Host “”)

-或-

DeliveryMethod 属性设置为 Network 零, Port 负数或大于 65,535。

此对象已被释放。

与 SMTP 服务器的连接失败。

-或-

身份验证失败。

-或-

操作超时。

-或-

EnableSsl 设置为 true ,但属性 DeliveryMethod 设置为 SpecifiedPickupDirectory 或 PickupDirectoryFromIis。

-或-

EnableSsl 设置为 true, SMTP 邮件服务器未在响应 EHLO 命令时播发 STARTTLS。

-或-

邮件无法传递到一个或多个收件人。recipients

无法将邮件传递到其中 To一个收件人, CC或者 Bcc。

邮件无法传递到两个或更多收件人,ToCC或者Bcc。

注解

若要在发送电子邮件或取消操作时接收通知,请将事件处理程序添加到事件 SendCompleted 。 可以通过调用SendAsync该方法来取消SendAsyncCancel操作。

呼叫 SendAsync后,必须等待电子邮件传输完成,然后尝试使用 Send 或 SendAsync发送另一封电子邮件。

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

如果 SMTP 主机需要凭据,则必须在调用此方法之前设置凭据。 若要指定凭据,请使用 UseDefaultCredentials 或 Credentials 属性。

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

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

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

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

若要在将邮件传输到 SMTP 服务器时发送邮件和阻止,请使用其中 Send 一种方法。

注释

如果属性 EnableSsl 设置为 true,并且 SMTP 邮件服务器不会在响应 EHLO 命令时播发 STARTTLS,则调用 Send 或 SendAsync 方法将引发一个 SmtpException。

适用于