SmtpClient 類別

定義

允許應用程式使用簡易郵件傳輸通訊協定 (SMTP) 傳送電子郵件。 此 SmtpClient 類型在某些平台上已經過時,不建議用於其他平臺;如需詳細資訊,請參閱一節。

public ref class SmtpClient : IDisposable
public ref class SmtpClient
public class SmtpClient : IDisposable
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public class SmtpClient : IDisposable
public class SmtpClient
type SmtpClient = class
    interface IDisposable
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
type SmtpClient = class
    interface IDisposable
type SmtpClient = class
Public Class SmtpClient
Implements IDisposable
Public Class SmtpClient
繼承
SmtpClient
屬性
實作

範例

下列程式代碼範例示範如何以異步方式傳送電子郵件訊息。

#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 伺服器以進行傳遞。 SMTP 通訊協定是在 RFC 2821 中定義,可在取得 https://www.ietf.org

重要

我們不建議您將 類別用於 SmtpClient 新的開發,因為 SmtpClient 不支援許多新式通訊協定。 請改用 MailKit 或其他連結庫。 如需詳細資訊,請參閱 不應該在 GitHub 上使用 SmtpClient

類別 SmtpClient 在 Xamarin 中已過時。 但是:

  • 它包含在 .NET Standard 2.0 和更新版本中,因此必須是任何支持這些版本的 .NET 實作的一部分。
  • 它存在,可用於 .NET Framework 4 到 .NET Framework 4.8。
  • 它可在 .NET Core 中使用,但不建議使用。

下表所示的類別是用來建構可使用 傳送 SmtpClient的電子郵件訊息。

類別 描述
Attachment 表示檔案附件。 這個類別可讓您將檔案、數據流或文字附加至電子郵件訊息。
MailAddress 代表寄件人和收件者的電子郵件位址。
MailMessage 代表電子郵件訊息。

若要使用 SmtpClient建構和傳送電子郵件訊息,您必須指定下列資訊:

  • 您用來傳送電子郵件的 SMTP 主機伺服器。 Host請參閱和 Port 屬性。

  • SMTP 伺服器需要驗證的認證。 請參閱 Credentials 屬性。

  • 寄件者的電子郵件地址。 Send請參閱 採用 from 參數的 和 SendAsync 方法。 另請參閱 MailMessage.From 屬性。

  • 收件者的電子郵件地址或位址。 Send請參閱 採用 recipient 參數的 和 SendAsync 方法。 另請參閱 MailMessage.To 屬性。

  • 訊息內容。 Send請參閱 採用 body 參數的 和 SendAsync 方法。 另請參閱 MailMessage.Body 屬性。

若要包含電子郵件訊息的附件,請先使用 Attachment 類別建立附件,然後使用 屬性將其新增至郵件 MailMessage.Attachments 。 根據收件者使用的電子郵件讀取器和附件的檔類型而定,某些收件者可能無法讀取附件。 對於無法以原始形式顯示附件的用戶端,您可以使用 屬性來指定替代檢視 MailMessage.AlternateViews

在 .NET Framework 中,您可以使用應用程式或計算機組態檔來指定所有SmtpClient物件的預設主機、埠和認證值。 如需詳細資訊,請參閱 <mailSettings> 元素 (網路設定) 。 .NET Core 不支援設定預設值。 因應措施是,您必須直接在 上 SmtpClient 設定相關的屬性。

若要傳送電子郵件訊息,並在等候電子郵件傳送至 SMTP 伺服器時封鎖,請使用其中一種同步 Send 方法。 若要允許程式的主線程在傳送電子郵件時繼續執行,請使用其中一個異步 SendAsync 方法。 當作業完成時SendAsync,就會SendCompleted引發 事件。 若要接收此事件,您必須將委派新增 SendCompletedEventHandlerSendCompleted。 委派 SendCompletedEventHandler 必須參考處理事件通知的 SendCompleted 回呼方法。 若要取消異步電子郵件傳輸,請使用 SendAsyncCancel 方法。

注意

如果有進行中的電子郵件傳輸,而您再次呼叫 SendAsyncSend ,您會收到 InvalidOperationException

如果應用程式想要將多個訊息傳送至相同的 SMTP 伺服器,則可能會重新使用 類別的 SmtpClient 目前實例所建立的連接。 當使用驗證或加密來建立 SMTP 伺服器的連線時,這特別有用。 驗證和建立 TLS 會話的程式可能是昂貴的作業。 將大量電子郵件傳送至相同的 SMTP 伺服器時,重新建立每個郵件的連線需求可能會對效能造成重大影響。 有許多大量電子郵件應用程式會傳送電子郵件狀態更新、電子報發佈或電子郵件警示。 此外,許多電子郵件用戶端應用程式都支援離線模式,用戶可以撰寫許多在建立SMTP伺服器連線時傳送的電子郵件訊息。 電子郵件用戶端通常會將所有 SMTP 訊息傳送到因特網服務提供者所提供的特定 SMTP 伺服器 (,) ,然後將此電子郵件轉寄給其他 SMTP 伺服器。

類別 SmtpClient 實作會集區 SMTP 連線,以避免對相同伺服器重新建立每個訊息的連線的額外負荷。 應用程式可能會重複使用相同的 SmtpClient 物件,將許多不同的電子郵件傳送至相同的 SMTP 伺服器和許多不同的 SMTP 伺服器。 因此,沒有任何方法可以判斷應用程式何時 SmtpClient 使用 物件完成,而且應該加以清除。

當 SMTP 工作階段完成且用戶端想要終止連線時,它必須將 QUIT 訊息傳送至伺服器,以指出它沒有要傳送的訊息。 這可讓伺服器從客戶端釋放與連線相關聯的資源,並處理用戶端所傳送的訊息。

類別 SmtpClient 沒有 Finalize 方法,因此應用程式必須呼叫 Dispose 以明確釋放資源。 方法 Dispose 會逐一查看屬性中指定的 Host SMTP 伺服器的所有已建立連線,並傳送 QUIT 訊息,然後依正常方式結束 TCP 連線。 方法 Dispose 也會釋放 所使用的 Socket Unmanaged 資源,並選擇性地處置 Managed 資源。

Dispose 使用完畢時,請呼叫 SmtpClientDispose 方法會將 SmtpClient 保留在無法使用的狀態。 呼叫 Dispose之後,您必須釋放 的所有參考, SmtpClient 讓垃圾收集行程可以回收佔用的 SmtpClient 記憶體。

建構函式

SmtpClient()

使用組態檔設定,初始化 SmtpClient 類別的新執行個體。

SmtpClient(String)

初始化 SmtpClient 類別的新執行個體,該類別使用指定的 SMTP 伺服器來傳送電子郵件。

SmtpClient(String, Int32)

初始化 SmtpClient 類別的新執行個體,該類別使用指定的 SMTP 伺服器和連接埠來傳送電子郵件。

屬性

ClientCertificates

指定應該用來建立 Secure Sockets Layer (SSL) 連線的憑證。

Credentials

取得或設定用來驗證寄件者的認證。

DeliveryFormat

取得或設定 SmtpClient 用來傳送電子郵件的傳遞格式。

DeliveryMethod

指定將要如何處理外送的電子郵件訊息。

EnableSsl

指定 SmtpClient 是否使用 Secure Sockets Layer (SSL) 加密連線。

Host

取得或設定用於 SMTP 交易的主機名稱或 IP 位址。

PickupDirectoryLocation

取得或設定資料夾,應用程式會在其中儲存要由本機 SMTP 伺服器處理的郵件訊息。

Port

取得或設定用於 SMTP 交易的連接埠。

ServicePoint

取得用來傳送電子郵件訊息的網路連線。

TargetName

取得或設定服務提供者名稱 (SPN),當使用延伸保護時會用此名稱進行驗證。

Timeout

取得或設定值,指定同步 Send 呼叫逾時的時間長度。

UseDefaultCredentials

取得或設定 Boolean 值,控制是否隨著要求傳送 DefaultCredentials

方法

Dispose()

將 QUIT 訊息傳送至 SMTP 伺服器、正常結束 TCP 連接,並且釋放 SmtpClient 類別之目前執行個體所使用的所有資源。

Dispose(Boolean)

將 QUIT 訊息傳送至 SMTP 伺服器、正常結束 TCP 連接、釋放 SmtpClient 類別之目前執行個體所使用的所有資源,並選擇性處置 Managed 資源。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
OnSendCompleted(AsyncCompletedEventArgs)

引發 SendCompleted 事件。

Send(MailMessage)

傳送指定的訊息給 SMTP 伺服器進行傳遞。

Send(String, String, String, String)

傳送指定的電子郵件訊息給 SMTP 伺服器進行傳遞。 訊息寄件者、收件者、主旨和訊息主體是使用 String 物件來指定。

SendAsync(MailMessage, Object)

傳送指定的電子郵件訊息給 SMTP 伺服器進行傳遞。 這個方法不會封鎖呼叫執行緒,而且允許呼叫端將物件傳遞給作業完成時所叫用 (Invoke) 的方法。

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

傳送電子郵件訊息給 SMTP 伺服器進行傳遞。 訊息寄件者、收件者、主旨和訊息主體是使用 String 物件來指定。 這個方法不會封鎖呼叫執行緒,而且允許呼叫端將物件傳遞給作業完成時所叫用 (Invoke) 的方法。

SendAsyncCancel()

取消傳送電子郵件訊息的非同步作業。

SendMailAsync(MailMessage)

傳送指定的訊息給 SMTP 伺服器以進行非同步作業形式的傳遞。

SendMailAsync(MailMessage, CancellationToken)

傳送指定的訊息給 SMTP 伺服器以進行非同步作業形式的傳遞。

SendMailAsync(String, String, String, String)

傳送指定的訊息給 SMTP 伺服器以進行非同步作業形式的傳遞。 訊息寄件者、收件者、主旨和訊息主體是使用 String 物件來指定。

SendMailAsync(String, String, String, String, CancellationToken)

以非同步作業方式,使用指定的寄件者、收件者、主旨與內文字串,將指定的郵件傳送到 SMTP 伺服器以進行傳遞。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

事件

SendCompleted

在非同步電子郵件傳送作業完成時發生。

適用於

另請參閱