Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
SmtpClient Class

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
SmtpClient Class

Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).

Namespace:  System.Net.Mail
Assembly:  System (in System.dll)
Visual Basic (Declaration)
Public Class SmtpClient
Visual Basic (Usage)
Dim instance As SmtpClient
C#
public class SmtpClient
Visual C++
public ref class SmtpClient
JScript
public class SmtpClient

The SmtpClient class is used to send e-mail to an SMTP server for delivery. The classes shown in the following table are used to construct e-mail 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 e-mail message.

MailAddress

Represents the e-mail address of the sender and recipients.

MailMessage

Represents an e-mail message.

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

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

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

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

  • The e-mail 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 e-mail 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 e-mail 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.

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

To send the e-mail message and block while waiting for the e-mail 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 e-mail 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 e-mail transmission, use the SendAsyncCancel method.

NoteNote:

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

SMTP is defined in RFC 2821, which is available at http://www.ietf.org.

TopicLocation
How to: Install and Configure SMTP Virtual Servers in IISConfiguring ASP .NET Web Applications
How to: Install and Configure SMTP Virtual Servers in IISConfiguring ASP .NET Web Applications
How to: Install and Configure SMTP Virtual Servers in IIS 6.0Building ASP .NET Web Applications in Visual Studio
How to: Install and Configure SMTP Virtual Servers in IIS 6.0Building ASP .NET Web Applications in Visual Studio

The following code example demonstrates sending an e-mail message asynchronously.

C#
using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
namespace Examples.SmptExamples.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 the the SMTP host.
            SmtpClient client = new SmtpClient(args[0]);
            // Specify the e-mail 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 e-mail message.
            MailAddress to = new MailAddress("ben@contoso.com");
            // Specify the message content.
            MailMessage message = new MailMessage(from, to);
            message.Body = "This is a test e-mail 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.");
        }
    }
}

Visual C++
#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 the the SMTP host.
        SmtpClient^ client = gcnew SmtpClient(args[1]);
        // Specify the e-mail 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 e-mail message.
        MailAddress^ to = gcnew MailAddress("ben@contoso.com");
        // Specify the message content.
        MailMessage^ message = gcnew MailMessage(from, to);
        message->Body = "This is a test e-mail 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!");
    }
}

System..::.Object
  System.Net.Mail..::.SmtpClient
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
VB .Net Example      Bashar Lulu - ATC ... Pepeman   |   Edit   |   Show History
Imports System
Imports System.Net
Imports System.Net.Mail
Imports System.Net.Mime
Imports System.Threading
Imports System.ComponentModel

Namespace Examples.SmptExamples.Async

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 = CType(e.UserState,String)
If e.Cancelled Then
Console.WriteLine("[{0}] Send canceled.", token)
End If
If (Not (e.Error) Is 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 the SMTP host.
Dim client As SmtpClient = New SmtpClient(args(0))
' Specify the e-mail sender.
' Create a mailing address that includes a UTF8 character
' in the display name.
Dim from As MailAddress = New MailAddress("jane@contoso.com", ("Jane " _
+ (CType(216,Char) + " Clayton")), System.Text.Encoding.UTF8)
' Set destinations for the e-mail message.
Dim to As MailAddress = New MailAddress("ben@contoso.com")
' Specify the message content.
Dim message As MailMessage = New MailMessage(from, to)
message.Body = "This is a test e-mail message sent by an application. "
' Include some non-ASCII characters in body and subject.
Dim someArrows As String = New String(New Char() {Microsoft.VisualBasic.ChrW(92), Microsoft.VisualBasic.ChrW(92), Microsoft.VisualBasic.ChrW(92), Microsoft.VisualBasic.ChrW(92)})
message.Body = (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 Me.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
Tags What's this?: Add a tag
Flag as ContentBug
rfc 2821 is obsolete      just.a.nerd   |   Edit   |   Show History

rfc 2821 is now obsolete. To find new info:

http://www.ietf.org/rfc/rfc5321.txt

Tags What's this?: Add a tag
Flag as ContentBug
Needed some additional info      MozillaKilled   |   Edit   |   Show History

I liked this Async article. Its great but it needed more info.

I use "Classic Hamster V2.1.0.11" mail server running SMTP on port 100 and so I needed this additional code:

// Command line argument must the the SMTP host.

SmtpClient client = newSmtpClient(args[0],100);

client.EnableSsl = false;

client.UseDefaultCredentials = false;

client.DeliveryMethod = SmtpDeliveryMethod.Network;

then...later on below the MailMessage object....

client.Credentials =

new System.Net.NetworkCredential(from.ToString(), "f00bar");
Tags What's this?: Add a tag
Flag as ContentBug
RFC 2821 diff RFC5321      Yogurt   |   Edit   |   Show History
This blog has some of the major changes:

http://blog.mailchannels.com/2008/10/update-to-email-standards.html


Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker