 .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. This server then relays the message to the correct destinations using the domain names from the email addresses specified.
The .NET framework provides the System.Net.Mail namespace for SMTP electronic mail functionality. This namespace contains several classes that are useful when sending email. The three key classes that will be considered in this article are SmtpClient, MailMessage and Attachment. These were all introduced in version 2.0 of the .NET framework.
SmtpClient Class
The SmtpClient class provides the functionality required to send email using an SMTP server. This class must be 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 instance of the SmtpClient class. Using a MailMessage object, more complex email messages can be distributed than with an SmtpClient object alone. These messages can include HTML-formatted text, attachments and prioritisation, depending upon the configuration of properties used.
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 electronic mail message.
Sending Email in .NET
The following sections explain how to send email from a .NET application. To begin, create a new console application and name it "SmtpDemo". In the initial Program class code name, add the following using directive to reference the required namespace:
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. This may be an SMTP server connected to a local network, such as a Microsoft Exchange server that is able to send SMTP email, or a server on the Internet, such as the SMTP server provided by most Internet Service Providers.
The server to be used is configured in the Host property of the SmtpServer object. The property holds a string containing either the name or the IP address of the server.
In the examples, we will hold the host name in a constant defined in the class. To add the constant to the Program class, add the following line in the class' code block, substituting "hostname" for the name of your SMTP server. NB: If you download the sample code, you must modify the constants mentioned in this article 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 into the Main method's code block:
SmtpClient client = new SmtpClient();
client.Host = SmtpHost;
Configuring the Server Port
Most SMTP servers are configured to send email using port 25. This is the default option for SMTP email but can be modified in the server's configuration. If the system administrator has modified the port, the new port value must be specified in the Port property of the SmtpClient. If your port configuration is non-standard, add the following constant to the class, using the correct port number:
const int SmtpPort = 25;
To use the configured port, set the Port property of the SmtpClient object in the Main method as follows:
client.Port = SmtpPort;
Configuring Credentials
Many SMTP configurations permit the sending of email without the client being authenticated. If the server that you are using requires authentication before you are allowed to send email, there are two possible manners in which to provide credentials. The first of these is to use the login details of the current user. This is achieved by setting the UseDefaultCredentials property to true.
If your SMTP server requires authentication and the default credentials are suitable, add the following line to the Main method:
client.UseDefaultCredentials = true;
In some cases, a specific set of credentials that are different to the current user's details must be provided before the SMTP server will send email on behalf of the client. In these cases, the UseDefaultCredentials property will not be sufficient. Instead, a specific login name and password must be provided using a NetworkCredential object.
The NetworkCredential class is found in the System.Net namespace. If your SMTP server requires specific credentials to be supplied, ensure that you have added using System.Net; to the top of the code file before adding the following lines of code to the Main method. Substitute "username" and "password" with the appropriate security information.
NetworkCredential cred = new NetworkCredential();
cred.UserName = "username";
cred.Password = "password";
NB: When using specific credentials, do not set the value of UseDefaultCredentials to true.
Some More Constants
In the examples that follow we will send email in a variety of ways. The email addresses that you use for sending and receiving email will be different from any that could be defined here. To make the samples easier to read and simpler to copy and paste into your own code, we will add several more constants to hold these addresses.
We will be using five email addresses in the examples. These will be the sender's email address, two recipient addresses and recipients for carbon copies and blind carbon copies. If you do not have the use of five email addresses you may want to duplicate some or set up some free Hotmail, Google or other web-based email accounts.
Add the following constants to the Program class, specifying valid email addresses for each.
const string SenderEmail = "test@...";
const string RecipientEmail1 = "test1@...";
const string RecipientEmail2 = "test2@...";
const string CcEmail = "testcc@...";
const string BccEmail = "testbcc@...";
Sending a Plain Text Email
Using the information from the previous sections, you should now have an SmtpClient object named "client" that is set up for your particular environment. You will also have some constants created that will make the examples simpler. We can test that the client is correctly configured by sending a simple email using the Send method. To send a plain text email, the Send method can be called with four string parameters. The parameters are in order:
- From Email Address. As the server is not aware of any email address of the current user, the email address that will appear in the "From" line must be specified.
- To Email Address. This is the address of the intended recipient.
- Subject. The subject of the email.
- Body. The text that will appear in the body of the email. This is plain text so no formatting is permitting although some escape characters can be used. For example, using "\n" is permitted to add a line break.
To send a plain text email, try executing the following code. This should appear directly after the configuration of the SMTP client:
client.Send(SenderEmail, RecipientEmail1, "Hello", "Hi.\nHow are you?");
Troubleshooting
If the above sample code will not execute or the email does not arrive, check the following:
- Is SMTP email blocked by the server you have used?
- Is the sender's email address valid? Some servers will only relay from known addresses.
- Is the recipient's email address correct?
- Is the SMTP server's host name correct? You may want to try the IP address instead.
- Is the SMTP port correct? This may have been reconfigured.
- Are the credentials you have supplied valid?
Using the MailMessage Class
As we have seen, SMTP email can be sent from a .NET application using only the SmtpClient class. However, this only permits a plain text email and has limited functionality. A second variation of the SmtpClient's Send method accepts a MailMessage object as its parameter. Using a MailMessage object, much more flexibility is introduced.
To send a simple email, similar to the one sent in the previous example, four properties of the MailMessage class are used. These are the From, To, Subject and Body properties. Unlike with the previously used overloaded version of the Send method, the four properties are not all string values.
The From property uses a MailAddress object as its value. The MailAddress class, in its simplest usable form, holds an email address. This email address can be passed in the object's constructor.
The To property holds a MailAddressCollection object. This collection class can hold many MailAddress objects and, as we will see later, this can be used when sending the same email to multiple recipients.
The Subject and Body properties are simple strings. As in the earlier example, the Body text can include some control characters such as carriage return escape codes.
To use the MailMessage class to send an identical message to the previous example, run the following code. This should appear after the "client" object is configured. Note how the From and To properties are initialised.
MailMessage message = new MailMessage();
message.From = new MailAddress(SenderEmail);
message.To.Add(new MailAddress(RecipientEmail1));
message.Subject = "Hello";
message.Body = "Hi.\nHow are you?";
client.Send(message);
Using Display Names
MailAddress objects contain an additional property that permits you to specify a real name in addition to an email address. In most email reader applications, such as Microsoft Outlook, this user-friendly name is displayed instead of, or alongside, the email address of both the recipient and sender. The DisplayName property can be set independently or, as shown in the next example, within the object's constructor.
MailMessage message = new MailMessage();
message.From = new MailAddress(SenderEmail, "Richard");
message.To.Add(new MailAddress(RecipientEmail1, "Lisa"));
message.Subject = "Hello";
message.Body = "Hi.\nHow are you?";
client.Send(message);
Adding Multiple Recipients
As the To property of the MailMessage class holds a collection of email addresses, we can add any number of recipients with each receiving a copy of the same message. This is achieved by simply adding more than one MailAddress object to the property. NB: Each recipient will be able to see all of the other recipient's addresses so this method should not be used if this information must be kept private.
MailMessage message = new MailMessage();
message.From = new MailAddress(SenderEmail, "Richard");
message.To.Add(new MailAddress(RecipientEmail1, "Lisa"));
message.To.Add(new MailAddress(RecipientEmail2, "Chris"));
message.Subject = "Hello";
message.Body = "Hi.\nHow are you?";
client.Send(message);
Adding a Reply To Address
Sometimes you will want to send an email from a specific email address but will want replies to the email to be received at an alternative address. In this case, you can add a "reply to" address using the ReplyTo property. The received email will show the same sender but replies will be redirected. The following example sends an email from Richard to Lisa but replies to the message will be sent to Chris.
MailMessage message = new MailMessage();
message.From = new MailAddress(SenderEmail, "Richard");
message.To.Add(new MailAddress(RecipientEmail1, "Lisa"));
message.ReplyTo = new MailAddress(RecipientEmail2, "Chris");
message.Subject = "Hello";
message.Body = "Hi.\nHow are you?";
client.Send(message);
Adding Carbon Copies and Blind Carbon Copies
When sending an email that is intended for one or more primary recipients, you may also want to send a copy to other, secondary recipients who would be interested in the message contents. To indicate that the email is not directly for those secondary people, they can be added as carbon copy (CC) recipients. These are visible to all recipients of the message.
As an alternative, email addresses can be added to the blind carbon copy (BCC) list. Recipients on this list receive the email as expected but their details are hidden from anyone else's view.
The following code sends an email and includes a CC and BCC address using the appropriately named "CC" and "Bcc" properties of the MailMessage object. Note that both lists accept multiple addresses using a MailAddressCollection.
MailMessage message = new MailMessage();
message.From = new MailAddress(SenderEmail);
message.To.Add(new MailAddress(RecipientEmail1));
message.CC.Add(new MailAddress(CcEmail));
message.Bcc.Add(new MailAddress(BccEmail));
message.Subject = "Hello";
message.Body = "Hi.\nHow are you?";
client.Send(message);
Adding Formatting to an Email
If you wish to send emails that include font and paragraph formatting, hyperlinks or images, you can HTML tags in the message body. To enable HTML, the IsBodyHtml property must be set to true. If this property is false, the message and tags will be sent in plain text.
The following sample sends the same message as we have sent previously. In this case, the "\n" control character is replaced with the break tag (<br>) and the first line of the message is highlighted with bold text.
MailMessage message = new MailMessage();
message.From = new MailAddress(SenderEmail);
message.To.Add(new MailAddress(RecipientEmail1));
message.Subject = "Hello";
message.IsBodyHtml = true;
message.Body = "<html><body><b>Hi.</b><br>How are you?</body></html>";
client.Send(message);
Setting an Email's Priority
By default, email messages are sent with normal priority. If desired, this importance of the email can be changed using the Priority property of the MailMessage class. This property accepts a value from the MailPriority enumeration. Possible values are High, Normal and Low.
The following code sends a high priority mail message:
MailMessage message = new MailMessage();
message.From = new MailAddress(SenderEmail);
message.To.Add(new MailAddress(RecipientEmail1));
message.Subject = "Hello";
message.Body = "Hi.\nHow are you?";
message.Priority = MailPriority.High;
client.Send(message);
Adding Attachments to an Email
One of the most useful elements of email is the option to send file attachments. The MailMessage class permits the addition of multiple attachments via the Attachments property. This property contains a collection, to which objects of the Attachment class may be added.
The Attachment class can be used to hold file or stream data. The simplest way to create an attachment is simply to pass the path and name of a file to attach as a string parameter of the class' constructor. This process is used in the example below to attach the "win.ini" file to the email. NB: Ensure that this file exists before running the code.
MailMessage message = new MailMessage();
message.From = new MailAddress(SenderEmail);
message.To.Add(new MailAddress(RecipientEmail1));
message.Subject = "Hello";
message.Body = "Hi.\nHow are you?";
message.Priority = MailPriority.High;
Attachment attachFile = new Attachment(@"c:\windows\win.ini");
message.Attachments.Add(attachFile);
client.Send(message);
|