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. SMTP 通訊協定定義于 RFC 2821 中,可在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. 如需詳細資訊,請參閱system.net.mail.smtpclient 不應在 GitHub 上使用。For more information, see SmtpClient shouldn't be used on GitHub.

SmtpClient 類別在 Xamarin 中已過時。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. 請參閱 HostPort 屬性。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 伺服器(由網際網路服務提供者提供),然後再將此電子郵件轉寄給其他 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 會話完成,而且用戶端想要終止連接時,它必須傳送一則訊息給伺服器,表示它沒有其他要傳送的訊息。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 伺服器的所有已建立連接,然後傳送結束訊息,接著正常地結束 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 所使用的非受控資源,並選擇性處置 managed 資源。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

指定應該用來建立 Secure Sockets Layer (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 是否使用 Secure Sockets Layer (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 值,控制是否隨著要求傳送 DefaultCredentialsGets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.

方法

Dispose()

將 QUIT 訊息傳送至 SMTP 伺服器、正常結束 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)

將 QUIT 訊息傳送至 SMTP 伺服器、正常結束 TCP 連接、釋放 SmtpClient 類別之目前執行個體所使用的所有資源,並選擇性處置 Managed 資源。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. 這個方法不會封鎖呼叫執行緒,而且允許呼叫端將物件傳遞給作業完成時所叫用 (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)

傳送電子郵件訊息給 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.

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

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

事件

SendCompleted

在非同步電子郵件傳送作業完成時發生。Occurs when an asynchronous email send operation completes.

適用於

另請參閱