Back to articles list

Email enhancements in .NET Framework 2.0 (2/28/2006)
System.Web.Mail is obsolete. Use System.Net.Mail instead. This is the first error that you will see when you try to compile your old codes in ASP .NET 1.X containing e-mail codes. In this article we don't mean to compare e-mail delivery for ASP .NET 1.x and 2.0. I try to have a briefing on how to setup and send e-mail from a .NET 2.0 application from scratch.

Configuration assumption.
 I assume that you are using windows 2003, IIS 6.0 and Visual Studio .NET 2005 or Visual Web Developer 2005 Express Edition. If you are using any other operating system or web server, kindly make any necessary adjustment.
General information about e-mail sending and SMTP
Most probably you have already worked with Microsoft Outlook or any mail client application. Receiving e-mail is out of scope of this article. As a web developer if we can manage to send our e-mail the job is done. We mostly need it for sending automated e-mails, News letters, sending forgotten passwords and etc. Let's see what we need to send e-mail using .NET code.
Step 1: Installing and Configuring SMTP Server
 Before doing anything we need a service to deliver the e-mail for us. This service is SMTP (Simple Mail Transfer Protocol) service that is an optional component, coming with Microsoft Windows. To install the service you can simply go to Control Panel -> Add/Remove Programs -> Add/Remove Windows Components. Then select Application Server and click Details... button, then Internet Information Services (IIS) and click Details... button and finally Check the SMTP Service. Click OK and finalize the installation. Now you have your mail server installed on your local machine.
 See the SMTP installation Screen shot here.
Once you complete the SMTP installation it starts the service but not really ready to send your e-mails. It needs a small configuration to have it working. To do so, just go to Administrative Tools -> Internet Information Services. Expand the local computer node and right-click on the Default SMTP Virtual Server and select the properties. Select the Access tab and click on Relay button.


You will see that by default your SMTP Server relays the e-mails only from an empty list (Actually no relay can happen by default). Assuming that all the developers are lazy (!?) and on our development environment we just want the things WORK, I simply change the relay restrictions to All except the list below. This is enough for my local SMTP Server do the job that I need. (NEVER MAKE THIS CONFIGURATION ON PRODUCTION SERVER. IT IS A LOVELY ACCESS POINT FOR SPAMMERS TO SEND E-MAIL SPAM USING YOUR MAIL SERVER AND FOR HACKERS TO ARRANGE A DENIAL OF SERVICE ATTACK).

Step 2: Constructing your e-mail message:
- Available classes and namespaces for e-mail in .NET 2.0
 Unlike .NET Framework 1.x which was very simple in fuctionality for mail delivery, Framework 2.0 provides a lot better set of classes and functions. I don't mean to go back to Framework 1.x age again but I just need to mention that System.Web.Mail namespace is obsolete. You cannot use it anymore.
To send e-mail using .NET Framework 2.0 you need to import System.Net.Mail. So as the first step go to the top of the page and add:
using System.Net.Mail;

- Constructing the e-mail message
To send an e-mail you should first construct a mail message. So simply create an object of type MailMessage.
MailMessage msg = new MailMessage();
Wonderful! A blank e-mail is just in front of you. Just imagin a normal e-mail and construct the e-mail message.
An e-mail should be sent from somebody to somebody. So simply assign it. Remember that an e-mail goes from somebody (which is always one person) to somebody (that can be many receivers).
msg.From = new MailAddress("somebody@dotnetking.com");
msg.To.Add("test1@dotnetking.com");
msg.To.Add("test2@dotnetking.com");
msg.To.Add("test3@dotnetking.com");

The mentioned code sends e-mail from somebody@dotnetking.com to 3 addresses (test1@dotnetking.com, test2@dotnetking.com, test3@dotnetking.com).
 What else do you need for an e-mail? That's right, you need the subject and e-mail body. That is not a big deal as well. Just assign it to Subject property.
msg.Subject = "My e-mail subject for test";
msg.Body = "This is the e-mail body from Alireza.";
It seems that the job is done, but... Professional web developers can simply tell you that this is not enough. When you send an e-mail you need a professional HTML format for the mail message that all the HTML tags work correctly. The current e-mail message that we constructed is just a simple text. To enable HTML tags in e-mail we need to explicitly mention that the e-mail message contains HTML contents that should be deliverd as is. To do that simply all the following line.
msg.IsBodyHtml = true;
In this case you can simple change your e-mail body to:
msg.Body = "This is the e-mail <b>body</b> from <br/>Alireza.";
Which makes the word "body" appear in bold face and the word Alireza appears on the next line.
This gives you extreme freedon in making an e-mail with HTML tags with graphics, links and etc. But what about other languages support. We all know that .NET framework string is unicode by default, but what about the mail server. Who can guarantee that the mail server by default assumes that e-mails are unicode? Lets be realistic. Support for unicode e-mail requires the mail server utilize a double bandwidth which in most cases is not required. So make sure your default e-mail is not unicode when you send it to SMTP Server unless you specify it yourself. You need to do that when you are sending other non latin characters in your e-mail (like Arabic characters). To do that you need to assign an encoding to your message body. This line of code will do the things:
msg.BodyEncoding = new UTF8Encoding();
but don't forget to import System.Text namespace, because the class UTF8Encoding is defined there.

- Adding attachments to your e-mail
So far so good. Now we only need to know how we can send attachment. That's also very simple. Simply create an object of type Attachment and specify the filename as the constructor parametere. Be careful about the parameter, because it required as physical path as file name. If you have the relative path just use Server.MapPath funtion to get the physical path. Once the attachment object is created you can simple add it to the message attachments collection.
Attachment atch = new Attachment(Server.MapPath("Somefile.dat"));
msg.Attachments.Add(atch);
By repeting the same lines you may add multiple attachment files but be careful about the attachment size that is defined in your SMTP Server. To check the attachment size limit simply open the Internet Information Services (IIS) Manager.Expand the local computer node and right-click on the Default SMTP Virtual Server and select Properties. Click on the Messages tab and see the limit message size which is 2048KB by default. So actually 2 MB Message size is your limit. If you need to send bigger attachments simple chenage the size limit or uncheck the limit message size. 

Our message is ready to be sent. All we need now is a mail client to transfer the message to the SMTP Server.

Step 3: Sending the constructed e-mail message
Our Mail Client object
 The .NET 2.0 class to communicate with SMTP Server is SmtpClient. The nice thing in the SmtpClient class is that it gives you almost all the capabilities of your Microsoft Outlook to configure sending an e-mail. Simply create an object of SmtpClient type and instantiate it. The constructor accepts a parameter which is actually your SMTP Server address. If your mail server is running on the same machine as your ASP .NET server you can use localhost, otherwise simply use the SMTP address that is provided by your ISP (usually as mail.yourwebsite.com). In this case most of the times the server requires authentication that you need to provide a valid username and password to the server. This authentication is required to stop spammers from abusing a free SMTP server on a public IP. To do so simply create an instance of NetworkCredential object and assign it to Credentials property of the SmtpClient object.
SmtpClient cln = new SmtpClient("mail.yourwebsite.com");
cln.Credentials = new NetworkCredential("username", "password");

Your mail client is ready and you can simply send the e-mail using this code.
cln.Send(msg);

Happy new E-mail

Try it yourself
 Most of the time developers are searching for a sample code that simply works. To satisfy those developers I just put it all together as a simple code fragment that just works.

Add to your page header:
using System.Net.Mail;
using System.Net;
using System.Text;


Here is the code that generates the e-mail message and sends the e-mail.
MailMessage msg = new MailMessage();
msg.From = new MailAddress("somebody@dotnetking.com");
msg.To.Add("test1@dotnetking.com");
msg.Subject = "My e-mail subject for test";
msg.IsBodyHtml = true;
msg.BodyEncoding = new UTF8Encoding();
msg.Body = "This is the e-mail <b>body</b> from <br/>Alireza.";
Attachment atch = new Attachment(Server.MapPath("Somefile.dat"));
msg.Attachments.Add(atch);
 SmtpClient cln = new SmtpClient("mail.yourwebsite.com");
cln.Credentials = new NetworkCredential("username", "password");
cln.Send(msg);

The above code fragment sends an e-mail from  somebody@dotnetking.com to test1@dotnetking.com that has the subject of  "My e-mail subject for test" and will display the following text:
This is the e-mail body from
Alireza.

This e-mail contains an attachment called Somefile.dat that we assume is located on the same folder as the web page that sends the e-mail. It uses an SMTP Server at the address of mail.yourwebsite.com that requires authentication and the username + password is a valid combination of credentials on the SMTP server.
For any comments or clarifications contact me at www.dotnetking.com/contactus.aspx.
Alireza Ahmadi Aliabadi
MVP, MCSD, MCDBA, MCT



Back to articles list

 

 -