
.NET 2.0+Sending SMTP Email
Many modern applications send email for a variety of purposes. These include sending email to customers, suppliers and other businesses or individuals or for reporting problems that have occurred whilst running a program. With .NET, sending mail is easy.
Simple Mail Transport Protocol
Simple Mail Transport Protocol (SMTP) is the standard for sending email via the Internet. It is used to send email messages to one or more recipients, including carbon copied and blind carbon copied recipients, using an SMTP server. The server relays the message to the correct destinations using the email addresses specified.
The .NET framework provides the System.Net.Mail namespace for SMTP email functionality. This namespace contains classes that are useful when sending email. Three key classes are SmtpClient, MailMessage and Attachment. These were introduced in .NET framework 2.0.
SmtpClient Class
The SmtpClient class provides the functionality required to send email using an SMTP server. This class is configured with the details of the SMTP server to be used, including security credentials where required. It is possible to send plain text email using this class alone.
MailMessage Class
The MailMessage class represents an email message that can be sent using an SmtpClient object. It allows more complex email messages than with an SmtpClient object alone. Messages can include HTML-formatted text, attachments and prioritisation.
Attachment Class
The Attachment class is used with MailMessage objects to add attachments to an email. Using Attachment objects, any type of file may be sent with an email message.
Sending Email in .NET
The following sections explain how to send email from a .NET application. To begin, create a new console application named "SmtpDemo". Add the following using directive to the code:
using System.Net.Mail;
Configuring an SmtpClient
When sending email using an SmtpClient object, the object must be configured to communicate with an SMTP server. The server may be connected to a local network, such as a Microsoft Exchange server, or be a server on the Internet. The server to be used is configured in the Host property of the SmtpServer object. The property holds a string containing the server's name or IP address.
In the examples, we will hold the host name in a constant. To define the constant, add the following line in the Program class' code block, substituting "hostname" for the name of your SMTP server. NB: If you download the sample code, you must modify the constants before executing the program.
const string SmtpHost = "hostname";
Within the Main method, we can now create a new SmtpClient object and specify the host name. Add the following code to the method:
SmtpClient client = new SmtpClient();
client.Host = SmtpHost;
21 April 2008