SmtpClient 类

定义

警告

此 API 现已过时。

允许应用程序使用简单邮件传输协议 (SMTP) 来发送电子邮件。Allows applications to send email by using the Simple Mail Transfer Protocol (SMTP). SmtpClient 类型现已过时。The SmtpClient type is now obsolete.

public ref class SmtpClient : IDisposable
[System.Obsolete("SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead")]
public class SmtpClient : IDisposable
type SmtpClient = class
    interface IDisposable
Public Class SmtpClient
Implements IDisposable
继承
SmtpClient
属性
实现

示例

下面的代码示例演示如何以异步方式发送电子邮件。The following code example demonstrates sending an email message asynchronously.

#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

注解

SmtpClient 类用于将电子邮件发送到 SMTP 服务器以便传递。The SmtpClient class is used to send email to an SMTP server for delivery. 在 RFC 2821 中定义了 SMTP 协议,该协议在https://www.ietf.org提供。The SMTP protocol is defined in RFC 2821, which is available at https://www.ietf.org.

重要

建议不要将 SmtpClient 类用于新开发,因为 SmtpClient 不支持很多新式协议。We don't recommend that you use the SmtpClient class for new development because SmtpClient doesn't support many modern protocols. 改为使用MailKit或其他库。Use MailKit or other libraries instead. 有关详细信息,请参阅 GitHub 上的system.net.mail.smtpclient 不应使用For more information, see SmtpClient shouldn't be used on GitHub.

Xamarin 中的 SmtpClient 类已过时。The SmtpClient class is obsolete in Xamarin. 但是:However:

  • 它包含在 .NET Standard 2.0 及更高版本中,因此必须属于支持这些版本的任何 .NET 实现。It is included in the .NET Standard 2.0 and later versions and therefore must be part of any .NET implementation that supports those versions.
  • 它存在并且可用于 .NET Framework 4 到 .NET Framework 4.8。It is present and can be used in .NET Framework 4 through .NET Framework 4.8.
  • 它在 .NET Core 中可用,但不建议使用它。It is usable in .NET Core, but its use isn't recommended.

下表中显示的类用于构造可以使用 SmtpClient发送的电子邮件。The classes shown in the following table are used to construct email messages that can be sent using SmtpClient.

实例Class 说明Description
Attachment 表示文件附件。Represents file attachments. 此类允许你将文件、流或文本附加到电子邮件。This class allows you to attach files, streams, or text to an email message.
MailAddress 表示发件人和收件人的电子邮件地址。Represents the email address of the sender and recipients.
MailMessage 表示电子邮件消息。Represents an email message.

若要使用 SmtpClient构造和发送电子邮件,必须指定以下信息:To construct and send an email message by using SmtpClient, you must specify the following information:

  • 用于发送电子邮件的 SMTP 主机服务器。The SMTP host server that you use to send email. 请参阅 "Host" 和 "Port" 属性。See the Host and Port properties.

  • 用于身份验证的凭据(如果 SMTP 服务器需要)。Credentials for authentication, if required by the SMTP server. 请参阅 Credentials 属性。See the Credentials property.

  • 发件人的电子邮件地址。The email address of the sender. 请参阅采用 from 参数的 SendSendAsync 方法。See the Send and SendAsync methods that take a from parameter. 另请参阅 MailMessage.From 属性。Also see the MailMessage.From property.

  • 收件人的电子邮件地址。The email address or addresses of the recipients. 请参阅采用 recipient 参数的 SendSendAsync 方法。See the Send and SendAsync methods that take a recipient parameter. 另请参阅 MailMessage.To 属性。Also see the MailMessage.To property.

  • 消息内容。The message content. 请参阅采用 body 参数的 SendSendAsync 方法。See the Send and SendAsync methods that take a body parameter. 另请参阅 MailMessage.Body 属性。Also see the MailMessage.Body property.

若要在电子邮件中包含附件,请首先使用 Attachment 类创建附件,然后使用 MailMessage.Attachments 属性将其添加到消息中。To include an attachment with an email message, first create the attachment by using the Attachment class, and then add it to the message by using the MailMessage.Attachments property. 由于收件人使用的电子邮件读取器和附件的文件类型,某些收件人可能无法读取附件。Depending on the email reader used by the recipients and the file type of the attachment, some recipients might not be able to read the attachment. 对于无法以其原始形式显示附件的客户端,可以使用 MailMessage.AlternateViews 属性指定替代视图。For clients that cannot display the attachment in its original form, you can specify alternate views by using the MailMessage.AlternateViews property.

在 .NET Framework 中,可以使用应用程序或计算机配置文件来指定所有 SmtpClient 对象的默认主机、端口和凭据值。In .NET Framework, you can use the application or machine configuration files to specify default host, port, and credentials values for all SmtpClient objects. 有关详细信息,请参阅<mailSettings> 元素(网络设置)For more information, see <mailSettings> Element (Network Settings). .NET Core 不支持设置默认值。.NET Core does not support setting defaults. 作为一种解决方法,必须直接在 SmtpClient 上设置相关属性。As a workaround, you must set the relevant properties on SmtpClient directly.

若要在等待电子邮件传输到 SMTP 服务器的同时发送电子邮件和阻止,请使用同步 Send 方法之一。To send the email message and block while waiting for the email to be transmitted to the SMTP server, use one of the synchronous Send methods. 若要在传输电子邮件时允许程序的主线程继续执行,请使用异步 SendAsync 方法之一。To allow your program's main thread to continue executing while the email is transmitted, use one of the asynchronous SendAsync methods. SendAsync 操作完成时,将引发 SendCompleted 事件。The SendCompleted event is raised when a SendAsync operation completes. 若要接收此事件,必须将 SendCompletedEventHandler 委托添加到 SendCompletedTo receive this event, you must add a SendCompletedEventHandler delegate to SendCompleted. SendCompletedEventHandler 委托必须引用回调方法,该方法可处理 SendCompleted 事件的通知。The SendCompletedEventHandler delegate must reference a callback method that handles notification of SendCompleted events. 若要取消异步电子邮件传输,请使用 SendAsyncCancel 方法。To cancel an asynchronous email transmission, use the SendAsyncCancel method.

备注

如果正在传输电子邮件,并再次调用 SendAsyncSend,则将收到 InvalidOperationExceptionIf there is an email transmission in progress and you call SendAsync or Send again, you will receive an InvalidOperationException.

如果应用程序希望向同一 SMTP 服务器发送多条消息,则可以重新使用 SmtpClient 类的当前实例建立到 SMTP 服务器的连接。The connection established by the current instance of the SmtpClient class to the SMTP server may be re-used if an application wishes to send multiple messages to the same SMTP server. 当使用身份验证或加密建立与 SMTP 服务器的连接时,此方法特别有用。This is particularly useful when authentication or encryption are used establish a connection to the SMTP server. 身份验证和建立 TLS 会话的过程可能是成本高昂的操作。The process of authenticating and establishing a TLS session can be expensive operations. 如果将大量电子邮件发送到相同的 SMTP 服务器,则为每条消息重新建立连接的要求可能会对性能产生重大影响。A requirement to re-establish a connection for each message when sending a large quantity of email to the same SMTP server could have a significant impact on performance. 有大量的大量电子邮件应用程序可发送电子邮件状态更新、新闻稿分发或电子邮件警报。There are a number of high-volume email applications that send email status updates, newsletter distributions, or email alerts. 此外,许多电子邮件客户端应用程序都支持脱机模式,用户可在此模式下撰写多封电子邮件,这些电子邮件稍后会在与 SMTP 服务器建立连接时发送。Also many email client applications support an off-line mode where users can compose many email messages that are sent later when a connection to the SMTP server is established. 通常,电子邮件客户端将所有 SMTP 邮件发送到特定的 SMTP 服务器(由 Internet 服务提供商提供),然后将此电子邮件转发给其他 SMTP 服务器。It is typical for an email client to send all SMTP messages to a specific SMTP server (provided by the Internet service provider) that then forwards this email to other SMTP servers.

SmtpClient 类实现对 SMTP 连接进行缓冲,使其可以避免在将每条消息重新建立到同一个服务器的连接时产生的开销。The SmtpClient class implementation pools SMTP connections so that it can avoid the overhead of re-establishing a connection for every message to the same server. 应用程序可以重复使用同一个 SmtpClient 对象将许多不同的电子邮件发送到相同的 SMTP 服务器和许多不同的 SMTP 服务器。An application may re-use the same SmtpClient object to send many different emails to the same SMTP server and to many different SMTP servers. 因此,无法确定何时使用 SmtpClient 对象完成应用程序的操作,并且应清理该对象。As a result, there is no way to determine when an application is finished using the SmtpClient object and it should be cleaned up.

当 SMTP 会话完成并且客户端希望终止连接时,它必须向服务器发送一条 QUIT 消息,指示它没有更多要发送的消息。When an SMTP session is finished and the client wishes to terminate the connection, it must send a QUIT message to the server to indicate that it has no more messages to send. 这允许服务器释放与客户端的连接关联的资源,并处理客户端发送的消息。This allows the server to free up resources associated with the connection from the client and process the messages which were sent by the client.

SmtpClient 类没有 Finalize 方法,因此应用程序必须调用 Dispose,以显式释放资源。The SmtpClient class has no Finalize method, so an application must call Dispose to explicitly free up resources. Dispose 方法可循环访问在 Host 属性中指定的 SMTP 服务器的所有已建立连接,并发送一条 QUIT 消息,并正确地结束 TCP 连接。The Dispose method iterates through all established connections to the SMTP server specified in the Host property and sends a QUIT message followed by gracefully ending the TCP connection. Dispose 方法还会释放 Socket 使用的非托管资源,并可以选择释放托管资源。The Dispose method also releases the unmanaged resources used by the Socket and optionally disposes of the managed resources.

在完成使用 Dispose 后,应调用 SmtpClientCall Dispose when you are finished using the SmtpClient. Dispose 方法使 SmtpClient 处于不可用状态。The Dispose method leaves the SmtpClient in an unusable state. 调用 Dispose后,必须释放对 SmtpClient 的所有引用,以便垃圾回收器可以回收 SmtpClient 占用的内存。After calling Dispose, you must release all references to the SmtpClient so the garbage collector can reclaim the memory that the SmtpClient was occupying.

构造函数

SmtpClient()

使用配置文件设置来初始化 SmtpClient 类的新实例。Initializes a new instance of the SmtpClient class by using configuration file settings.

SmtpClient(String)

初始化 SmtpClient 类的新实例,该类使用指定的 SMTP 服务器发送电子邮件。Initializes a new instance of the SmtpClient class that sends email by using the specified SMTP server.

SmtpClient(String, Int32)

初始化 SmtpClient 类的新实例,该类使用指定的 SMTP 服务器和端口发送电子邮件。Initializes a new instance of the SmtpClient class that sends email by using the specified SMTP server and port.

属性

ClientCertificates

指定应该使用哪些证书来建立安全套接字层 (SSL) 连接。Specify which certificates should be used to establish the Secure Sockets Layer (SSL) connection.

Credentials

获取或设置用于验证发件人身份的凭据。Gets or sets the credentials used to authenticate the sender.

DeliveryFormat

获取或设置 SmtpClient 用于发送电子邮件的传递格式。Gets or sets the delivery format used by SmtpClient to send email.

DeliveryMethod

指定处理发出的电子邮件的方法。Specifies how outgoing email messages will be handled.

EnableSsl

指定 SmtpClient 是否使用安全套接字层 (SSL) 加密连接。Specify whether the SmtpClient uses Secure Sockets Layer (SSL) to encrypt the connection.

Host

获取或设置用于 SMTP 事务的主机名或主机 IP 地址。Gets or sets the name or IP address of the host used for SMTP transactions.

PickupDirectoryLocation

获取或设置文件夹,应用程序在该文件夹中保存电子邮件供本地 SMTP 服务器处理。Gets or sets the folder where applications save mail messages to be processed by the local SMTP server.

Port

获取或设置用于 SMTP 事务的端口。Gets or sets the port used for SMTP transactions.

ServicePoint

获取用于传输电子邮件的网络连接。Gets the network connection used to transmit the email message.

TargetName

获取或设置在使用扩展保护时用于身份验证的服务提供程序名称 (SPN)。Gets or sets the Service Provider Name (SPN) to use for authentication when using extended protection.

Timeout

获取或设置一个值,该值指定同步 Send 调用超时后的时间。Gets or sets a value that specifies the amount of time after which a synchronous Send call times out.

UseDefaultCredentials

获取或设置 Boolean 值,该值控制 DefaultCredentials 是否随请求一起发送。Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.

方法

Dispose()

向 SMTP 服务器发送一条 QUIT 消息,适当地结束 TCP 连接,并释放由 SmtpClient 类的当前实例使用的所有资源。Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, and releases all resources used by the current instance of the SmtpClient class.

Dispose(Boolean)

向 SMTP 服务器发送一条 QUIT 消息,适当地结束 TCP 连接,释放由 SmtpClient 类的当前实例使用的所有资源,并根据需要释放托管资源。Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, releases all resources used by the current instance of the SmtpClient class, and optionally disposes of the managed resources.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
OnSendCompleted(AsyncCompletedEventArgs)

引发 SendCompleted 事件。Raises the SendCompleted event.

Send(MailMessage)

将指定邮件发送到进行传递的 SMTP 服务器。Sends the specified message to an SMTP server for delivery.

Send(String, String, String, String)

将指定的电子邮件发送到 SMTP 服务器以便传递。Sends the specified email message to an SMTP server for delivery. 使用 String 对象指定邮件的发件人、收件人、主题和邮件正文。The message sender, recipients, subject, and message body are specified using String objects.

SendAsync(MailMessage, Object)

将指定的电子邮件发送到 SMTP 服务器以便传递。Sends the specified email message to an SMTP server for delivery. 此方法不阻止调用线程,并允许调用方将对象传递给操作完成后调用的方法。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)

将电子邮件发送到 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. 此方法不阻止调用线程,并允许调用方将对象传递给操作完成后调用的方法。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.

SendAsyncCancel()

取消异步操作以发送电子邮件。Cancels an asynchronous operation to send an email message.

SendMailAsync(MailMessage)

将指定的邮件以异步操作形式发送给 SMTP 服务器供传递。Sends the specified message to an SMTP server for delivery as an asynchronous operation.

SendMailAsync(String, String, String, String)

将指定的邮件以异步操作形式发送给 SMTP 服务器供传递。Sends the specified message to an SMTP server for delivery as an asynchronous operation. .. 使用 String 对象指定邮件的发件人、收件人、主题和邮件正文。The message sender, recipients, subject, and message body are specified using String objects.

ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)

事件

SendCompleted

在异步电子邮件发送操作完成时出现。Occurs when an asynchronous email send operation completes.

适用于

另请参阅