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请参阅采用参数的 fromSendAsync 方法。 另请参阅 属性 MailMessage.From

  • 收件人的电子邮件地址。 Send请参阅采用参数的 recipientSendAsync 方法。 另请参阅 属性 MailMessage.To

  • 检索消息内容。 Send请参阅采用参数的 bodySendAsync 方法。 另请参阅 属性 MailMessage.Body

若要包含电子邮件附件,请先使用 Attachment 类创建附件,然后使用 属性将其添加到邮件 MailMessage.Attachments 中。 根据收件人使用的电子邮件阅读器和附件的文件类型,某些收件人可能无法阅读附件。 对于无法以原始形式显示附件的客户端,可以使用 属性指定备用视图 MailMessage.AlternateViews

在 .NET Framework 中,可以使用应用程序或计算机配置文件为所有对象指定默认的主机、端口和凭据值SmtpClient。 有关详细信息,请参阅 <mailSettings> 元素 (网络设置) 。 .NET Core 不支持设置默认值。 解决方法是,必须直接在 上 SmtpClient 设置相关属性。

若要在等待电子邮件传输到 SMTP 服务器时发送电子邮件并阻止,请使用同步 Send 方法之一。 若要在传输电子邮件时允许程序的main线程继续执行,请使用其中一种异步SendAsync方法。 当 SendCompleted 操作完成时 SendAsync ,将引发 事件。 若要接收此事件,必须将委托添加到 SendCompletedEventHandlerSendCompleted。 委托 SendCompletedEventHandler 必须引用处理事件通知的 SendCompleted 回调方法。 若要取消异步电子邮件传输,请使用 SendAsyncCancel 方法。

注意

如果正在进行电子邮件传输,并且你再次拨打 SendAsyncSend ,你将收到 InvalidOperationException

如果应用程序希望向同一 SMTP 服务器发送多条消息,则类的当前实例 SmtpClient 建立的连接可以重新使用。 在使用身份验证或加密建立与 SMTP 服务器的连接时,这尤其有用。 身份验证和建立 TLS 会话的过程可能代价高昂。 向同一 SMTP 服务器发送大量电子邮件时,要求重新建立每条消息的连接可能会对性能产生重大影响。 有许多大量电子邮件应用程序用于发送电子邮件状态更新、新闻稿分发或电子邮件警报。 此外,许多电子邮件客户端应用程序支持一种线下模式,用户可以撰写许多电子邮件,这些电子邮件稍后在与 SMTP 服务器建立连接时发送。 电子邮件客户端通常会将所有 SMTP 邮件发送到 Internet 服务提供商提供的特定 SMTP 服务器 () ,然后将此电子邮件转发到其他 SMTP 服务器。

SmtpClient 实现将 SMTP 连接池化,以避免重新建立与同一服务器的每条消息的连接开销。 应用程序可以重复使用同一 SmtpClient 对象将许多不同的电子邮件发送到同一 SMTP 服务器和许多不同的 SMTP 服务器。 因此,无法确定应用程序何时完成使用 对象 SmtpClient ,应将其清理。

当 SMTP 会话完成并且客户端希望终止连接时,它必须向服务器发送 QUIT 消息,以指示它没有更多要发送的消息。 这允许服务器从客户端释放与连接关联的资源,并处理客户端发送的消息。

SmtpClient 没有 Finalize 方法,因此应用程序必须调用 Dispose 以显式释放资源。 方法 Dispose 循环访问属性中指定的 Host SMTP 服务器的所有已建立连接,并发送 QUIT 消息,然后正常结束 TCP 连接。 方法 Dispose 还释放 由 使用的非托管资源, Socket 并选择性地释放托管资源。

在完成使用 Dispose 后,应调用 SmtpClientDispose 方法使 SmtpClient 处于不可用状态。 调用 Dispose后,必须释放对 SmtpClient 的所有引用,以便垃圾回收器可以回收 占用的内存 SmtpClient

构造函数

SmtpClient()

使用配置文件设置来初始化 SmtpClient 类的新实例。

SmtpClient(String)

初始化 SmtpClient 类的新实例,该类使用指定的 SMTP 服务器发送电子邮件。

SmtpClient(String, Int32)

初始化 SmtpClient 类的新实例,该类使用指定的 SMTP 服务器和端口发送电子邮件。

属性

ClientCertificates

指定应该使用哪些证书来建立安全套接字层 (SSL) 连接。

Credentials

获取或设置用于验证发件人身份的凭据。

DeliveryFormat

获取或设置 SmtpClient 用于发送电子邮件的传递格式。

DeliveryMethod

指定处理发出的电子邮件的方法。

EnableSsl

指定 SmtpClient 是否使用安全套接字层 (SSL) 加密连接。

Host

获取或设置用于 SMTP 事务的主机名或主机 IP 地址。

PickupDirectoryLocation

获取或设置文件夹,应用程序在该文件夹中保存电子邮件供本地 SMTP 服务器处理。

Port

获取或设置用于 SMTP 事务的端口。

ServicePoint

获取用于传输电子邮件的网络连接。

TargetName

获取或设置在使用扩展保护时用于身份验证的服务提供程序名称 (SPN)。

Timeout

获取或设置一个值,该值指定同步 Send 调用超时后的时间。

UseDefaultCredentials

获取或设置 Boolean 值,该值控制 DefaultCredentials 是否随请求一起发送。

方法

Dispose()

向 SMTP 服务器发送一条 QUIT 消息,适当地结束 TCP 连接,并释放由 SmtpClient 类的当前实例使用的所有资源。

Dispose(Boolean)

向 SMTP 服务器发送一条 QUIT 消息,适当地结束 TCP 连接,释放由 SmtpClient 类的当前实例使用的所有资源,并根据需要释放托管资源。

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 服务器以便传递。 此方法不阻止调用线程,并允许调用方将对象传递给操作完成后调用的方法。

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

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

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

在异步电子邮件发送操作完成时出现。

适用于

另请参阅