
.NET 2.0+Sending SMTP Email (2)
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.
Configuring the Server Port
Most SMTP servers are configured to send email using port 25, though this can be modified in the server's configuration. If the system administrator has modified the port, the correct port must be specified in the SmtpClient's Port property. If your port configuration is non-standard, add the following constant to the class, using the correct port number:
To use the configured port, set the Port property of the SmtpClient object as follows:
Configuring Credentials
Some SMTP servers permit the sending of email without authentication. If the server that you are using requires authentication there are two ways to provide it. The first 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 must be provided before the server will send email. In these cases, the UseDefaultCredentials property will be insufficient. 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 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 need 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 use free 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@...";
21 April 2008