Breyta

Deila með


SmtpClient Class

Definition

Allows applications to send email by using the Simple Mail Transfer Protocol (SMTP). The SmtpClient type is obsolete on some platforms and not recommended on others; for more information, see the Remarks section.

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
Inheritance
SmtpClient
Attributes
Implements

Examples

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;
        delete client;
        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();
            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

Remarks

The SmtpClient class is used to send email to an SMTP server for delivery. The SMTP protocol is defined in RFC 2821, which is available at https://www.ietf.org.

Important

We don't recommend that you use the SmtpClient class for new development because SmtpClient doesn't support many modern protocols. Use MailKit or other libraries instead. For more information, see SmtpClient shouldn't be used on GitHub.

The SmtpClient class is obsolete in Xamarin. However:

  • 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.
  • It is present and can be used in .NET Framework 4 through .NET Framework 4.8.
  • It is usable in .NET Core, but its use isn't recommended.

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.

To construct and send an email message by using SmtpClient, you must specify the following information:

  • The SMTP host server that you use to send email. See the Host and Port properties.

  • Credentials for authentication, if required by the SMTP server. See the Credentials property.

  • The email address of the sender. See the Send and SendAsync methods that take a from parameter. Also see the MailMessage.From property.

  • The email address or addresses of the recipients. See the Send and SendAsync methods that take a recipient parameter. Also see the MailMessage.To property.

  • The message content. See the Send and SendAsync methods that take a body parameter. Also see the MailMessage.Body property.

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. For clients that cannot display the attachment in its original form, you can specify alternate views by using the MailMessage.AlternateViews property.

In .NET Framework, you can use the application or machine configuration files to specify default host, port, and credentials values for all SmtpClient objects. For more information, see <mailSettings> Element (Network Settings). .NET Core does not support setting defaults. As a workaround, you must set the relevant properties on SmtpClient directly.

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. To allow your program's main thread to continue executing while the email is transmitted, use one of the asynchronous SendAsync methods. The SendCompleted event is raised when a SendAsync operation completes. To receive this event, you must add a SendCompletedEventHandler delegate to SendCompleted. The SendCompletedEventHandler delegate must reference a callback method that handles notification of SendCompleted events. To cancel an asynchronous email transmission, use the SendAsyncCancel method.

Note

If there is an email transmission in progress and you call SendAsync or Send again, you will receive an InvalidOperationException.

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. This is particularly useful when authentication or encryption are used establish a connection to the SMTP server. The process of authenticating and establishing a TLS session can be expensive operations. 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. 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. 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.

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. 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. As a result, there is no way to determine when an application is finished using the SmtpClient object and it should be cleaned up.

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.

The SmtpClient class has no Finalize method, so an application must call Dispose to explicitly free up resources. 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. The Dispose method also releases the unmanaged resources used by the Socket and optionally disposes of the managed resources.

Call Dispose when you are finished using the SmtpClient. The Dispose method leaves the SmtpClient in an unusable state. After calling Dispose, you must release all references to the SmtpClient so the garbage collector can reclaim the memory that the SmtpClient was occupying.

Constructors

SmtpClient()

Initializes a new instance of the SmtpClient class by using configuration file settings.

SmtpClient(String, Int32)

Initializes a new instance of the SmtpClient class that sends email by using the specified SMTP server and port.

SmtpClient(String)

Initializes a new instance of the SmtpClient class that sends email by using the specified SMTP server.

Properties

ClientCertificates

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

Gets or sets the delivery format used by SmtpClient to send email.

DeliveryMethod

Specifies how outgoing email messages will be handled.

EnableSsl

Specify whether the SmtpClient uses Secure Sockets Layer (SSL) to encrypt the connection.

Host

Gets or sets the name or IP address of the host used for SMTP transactions.

PickupDirectoryLocation

Gets or sets the folder where applications save mail messages to be processed by the local SMTP server.

Port

Gets or sets the port used for SMTP transactions.

ServicePoint

Gets the network connection used to transmit the email message.

TargetName

Gets or sets the Service Provider Name (SPN) to use for authentication when using extended protection.

Timeout

Gets or sets a value that specifies the amount of time after which a synchronous Send call times out.

UseDefaultCredentials

Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.

Methods

Dispose()

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)

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.

(Inherited from Object)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
OnSendCompleted(AsyncCompletedEventArgs)

Raises the SendCompleted event.

Send(MailMessage)

Sends the specified message to an SMTP server for delivery.

Send(String, String, String, String)

Sends the specified email message to an SMTP server for delivery. The message sender, recipients, subject, and message body are specified using String objects.

SendAsync(MailMessage, Object)

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)

Sends an email message to an SMTP server for delivery. 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, CancellationToken)

Sends the specified message to an SMTP server for delivery as an asynchronous operation.

SendMailAsync(MailMessage)

Sends the specified message to an SMTP server for delivery as an asynchronous operation.

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

Sends the specified message to an SMTP server for delivery as an asynchronous operation, using the specified sender, recipients, subject, and body strings.

SendMailAsync(String, String, String, String)

Sends the specified message to an SMTP server for delivery as an asynchronous operation. The message sender, recipients, subject, and message body are specified using String objects.

ToString()

Returns a string that represents the current object.

(Inherited from Object)

Events

SendCompleted

Occurs when an asynchronous email send operation completes.

Applies to

See also