Click here to Skip to main content
15,885,278 members
Articles / Web Development / IIS
Article

Email System Using ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.46/5 (28 votes)
15 Nov 2005CPOL4 min read 193.5K   5.1K   97   39
The article explores the SMTP concepts, configuration and simple mail service.

Image 1

Introduction

This article explores the features of an email system developed in a simple manner and shows how to create a simple mail service without taking much effort. I am confident that whoever reads this article will get a fairly good idea about the email service and the concepts behind the mail server which is based on SMTP.

The problem

How often you come across problems that are caused due to the lack of technical knowledge and the core concepts behind the framework. This article explores the concepts behind the mail server in a most simple manner. The article:

  • Explores the configuration settings of a mail server using SMTP.
  • Describes the code in a very interesting and simple manner.
  • Describes the settings to be done for hosting it in a web server.
  • Describes the solutions to the problems that occur during runtime.

Exploring the technology

SMTP stands for Simple Mail Transfer Protocol. The emails are sent using this perfect protocol. The .NET Framework supplies the SMTP class that enables you to send simple e-mail messages. If you have to send an e-mail with added functionalities, you have to make use of the MailMessage class. With the help of this class, you can insert attachments, set priorities, etc. very easily. You can also send HTML e-mail using this class.

Pre-requisites for the mail server

First of all, you have to check whether the SMTP service is enabled in the IIS which is the Internet Information service (it's a Windows component shipped with the operating system). You can check this service in the Add/Remove section seen in the control panel:

Image 2

Click the Windows Component in the Add/Remove Programs section and you will get the screen shown below:

Image 3

See whether IIS is checked or not, if it is checked (installed) click IIS (Internet Information Services) and you will get the screen shown below:

Image 4

Then, check whether the SMTP service is installed or not. If the service is not available, you have to select the SMTP service and follow the wizard. Sometimes it may ask for the Windows XP CD for installing the Windows component. Now the SMTP mail service is available for the application.

Configuration and settings

For configuring the SMTP server you have to follow the steps given below:

  1. Go to>Start Menu>Control Panel>Administrator Tools>Internet Information Services.
  2. Click the Internet Information Services and locate the Default SMTP Virtual Server.
  3. Right click the same and go to the properties as seen below:

    Image 5

    Do the settings as per the figure by selecting your own IP address.

  4. Then go to the Access option in the tab menu and click Relay Restrictions. In Relay you will see the screen shown below and now configure accordingly:

    Image 6

    In the Access tab you have to configure the connection property also, as per the figure shown below and leave all the other settings as it is:

    Image 7

    The IP address 127.0.0.1 represents the localhost. Now you are ready for the application.

Code snippets

The code snippet for this project is explained below:

C#
private void SendMail()
{
  try
   {
     MailMessage Email=new MailMessage(); //Creating the Mail Message 
                                          //object.
     Email.To=txtTo.Text;                 //Storing the To value in 
                                          //the object.
     Email.From=txtFrom.Text;             //Storing the From value 
                                          //in the object.
     Email.Cc=txtCC.Text;                 //Storing the CC value in 
                                          //the object.
     Email.Bcc=txtBCC.Text;               //Storing the BCC value in 
                                          //the object.
     Email.Subject=txtSubject.Text;       //Storing the Subject value 
                                          //in the object.
     Email.Body=txtMessage.Text;          //Specifies the email body.
     Email.Priority=MailPriority.High;    //Setting priority to the mail 
                                          //as high,low,or normal
     Email.BodyFormat=MailFormat.Text;    //Formatting the mail as html 
                                          //or text.

     //Checking whether the attachment is needed or not.
     if(rbtnAttach.Checked)
     {
       //Adding attachment to the mail.
       Email.Attachments.Add(
                  new MailAttachment(FileBrowse.Value));

     }
     //Specifying the real SMTP Mail Server.
     SmtpMail.SmtpServer.Insert(0,"127.0.0.1");
     SmtpMail.Send(Email);                //Sending the mail.
     Reset();                             //calling the reset method to 
                                          //erase the text entered.
     lblMessage.ForeColor=Color.Navy;
     lblMessage.Text=
         "*Your email has been sent successfully-Thank You";
   }
   //Handling the Exception
   catch(Exception exc)
   {
     lblMessage.Text="Send error:"+exc.ToString();
     lblMessage.ForeColor=Color.Red;
   }
}

Call the SendMail() method in the Click event of the button as shown below:

C#
private void btnSend_Click(object sender, System.EventArgs e)
{
  SendMail();
}

The code block in the Reset() method is given below:

C#
private void Reset()
{
   //Seeking for the controls in the active webform.
   Control myForm=Page.FindControl("Form1");
   //Iterating each control.
   foreach(Control ctl in myForm.Controls)
   {
      // Checking whether it is a text box 
      // and clear when it is a textbox
      if(ctl.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox"))
      ((TextBox)ctl).Text="";
   }
}

Call the Reset() method in another Click event of the button as shown below:

C#
private void btnCancel_Click(object sender, System.EventArgs e)
{
    Reset();
}

Final solution

Our code now looks like this:

C#
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Mail;
namespace Email
{
    /// <summary>
    /// Summary description for WebForm1.
    /// </summary>
    public class WebForm1 : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.Label lblFrom;
        protected System.Web.UI.WebControls.Label lblCC;
        protected System.Web.UI.WebControls.TextBox txtFrom;
        protected System.Web.UI.WebControls.TextBox txtCC;
        protected System.Web.UI.WebControls.TextBox txtTo;
        protected System.Web.UI.WebControls.Label lblTo;
        protected System.Web.UI.WebControls.Label lblEmailService;
        protected System.Web.UI.WebControls.TextBox txtBCC;
        protected System.Web.UI.WebControls.Label lblBCC;
        protected System.Web.UI.WebControls.Label lblSubject;
        protected System.Web.UI.WebControls.TextBox txtSubject;
        protected System.Web.UI.WebControls.Label lblMessage;
        protected System.Web.UI.WebControls.TextBox txtMessage;
        protected System.Web.UI.WebControls.Button btnSend;
        protected System.Web.UI.HtmlControls.HtmlInputFile FileBrowse;
        protected System.Web.UI.WebControls.Label lblAttachment;
        protected System.Web.UI.WebControls.RadioButton rbtnAttach;
        protected System.Web.UI.WebControls.RadioButton rbtnDetachment;
        protected System.Web.UI.WebControls.Button btnCancel;
        public string strAttachment;
        
        private void Page_Load(object sender, System.EventArgs e)
        {
            lblMessage.Text="";
        }
        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the 
            // ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }
        
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        { 
            this.rbtnDetachment.CheckedChanged += 
               new System.EventHandler(this.rbtnDetachment_CheckedChanged);
            this.btnCancel.Click += 
                new System.EventHandler(this.btnCancel_Click);
            this.btnSend.Click += 
                new System.EventHandler(this.btnSend_Click);
            this.rbtnAttach.CheckedChanged += 
                new System.EventHandler(this.rbtnAttach_CheckedChanged);
            this.Load += new System.EventHandler(this.Page_Load);
        }
        #endregion
        
        //Method for sending the email
        //***************************************************************
        private void SendMail()
        {
            try
            {
                //Creating the Mail Message object.
                MailMessage Email=new MailMessage();
                //Storing the To value in the object reference.
                Email.To=txtTo.Text;                
                //Storing the From value in the object reference.
                Email.From=txtFrom.Text;
                //Storing the CC value in the object reference.
                Email.Cc=txtCC.Text;
                //Storing the BCC value in the object reference.
                Email.Bcc=txtBCC.Text;
                //Storing the Subject value in the object reference.
                Email.Subject=txtSubject.Text;
                //Specifies the email body.
                Email.Body=txtMessage.Text;
                //Setting priority to the mail as high,low,or normal
                Email.Priority=MailPriority.High;
                //Formatting the mail as html or text.
                Email.BodyFormat=MailFormat.Text;
                //Checking whether the attachment is needed or not.
                if(rbtnAttach.Checked)
                {
                    //Adding attachment to the mail.
                    Email.Attachments.Add(
                        new MailAttachment(FileBrowse.Value));
                }
                //specifying the real SMTP Mail Server.
                SmtpMail.SmtpServer.Insert(0,"127.0.0.1");
                SmtpMail.Send(Email);//Sending the mail.
                //calling the reset method to erase all the data 
                //after sending the mail.
                Reset();
                lblMessage.ForeColor=Color.Navy;
                //User information after submission.
                lblMessage.Text=
                  "*Your email has been sent successfully-Thank You";
            }
            //Catching Exception 
            catch(Exception exc)
            { 
                Reset();
                lblMessage.Text="Send error:"+exc.ToString();
                lblMessage.ForeColor=Color.Red;
            }
        }
        //Method to reset the text fields.
        //***********************************************************
        private void Reset()
        {
            //Seeking for the controls in the active webform.
            Control myForm=Page.FindControl("Form1");
            //Iterating each control.
            foreach(Control ctl in myForm.Controls)
            {
                //Checking whether it is a text
                //box and clear when it is a textbox.
                if(ctl.GetType().ToString().Equals(
                            "System.Web.UI.WebControls.TextBox")) 
                                                                 
                ((TextBox)ctl).Text="";
            }
        }
        //Event fires for sending the mail.
        //***********************************************************
        private void btnSend_Click(object sender, System.EventArgs e)
        {
            SendMail();
        }
        //Event for cancelling the mail.
        //***********************************************************
        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            Reset();
        }
        //Event for enabling or disabling the File browser.
        //************************************************************
        private void rbtnAttach_CheckedChanged(object sender, 
                                                  System.EventArgs e)
        {
            FileBrowse.Disabled=false;
        }
        //Event for enabling or disabling the File browser.
        //************************************************************
        private void rbtnDetachment_CheckedChanged(object sender, 
                                                        System.EventArgs e)
        {
            FileBrowse.Disabled=true;
        }
        //*************************************************************
    }
}

Using the solution

Download the source code files given above in the zip format and copy the contents into the root directory (e.g. C:\Inetpub\wwwroot). Go to the Internet Information Services and create a virtual directory named EmailSystem and give the correct path for mapping.

Solutions for some problems

The Error "Could not access 'CDO.Message' object"

Solution1

Specify a valid mail server for the SmtpMail.SmtpServer property. If that property is not set, set it to 127.0.0.1 or localhost. For example: SmtpMail.SmtpServer = "127.0.0.1".

Solution2

If you are using "localhost" or "127.0.0.1" as the SmtpMail.SmtpServer, you may not have permissions to relay through the IIS SMTP service. To allow access, open up IIS MMC in the Administrator tools option. Seek the SMTP virtual server, and right-click, then select the properties. On the Access tab, click the Relay Restriction button. In the Relay Restrictions dialog, grant your IP address (127.0.0.1) to the computer ListBox. Close all the dialogs, and restart the SMTP service again.

Solution3

If you are using "localhost" or "127.0.0.1" as the SmtpMail.SmtpServer, make sure that Anonymous access is allowed. To allow Access, open up IIS Admin MMC. Locate the SMTP virtual server, and right-click, then select the properties. On the Access tab, click the Authentication button. Then make sure "Anonymous Access" is the only checkbox checked. Close all the dialogs, and restart the SMTP service.

The transport failed to connect

Solution1

The above error is a network related error. Now, make sure the server System.Web.Mail is executing. Some times firewalls or proxy servers can cause problems. Try specifying the value by IP address. Poor DNS resolution can sometimes hinder name lookups. Check that the mail server is running at port 25. If you did not specify a SmtpMail.SmtpServer property, or if SmtpMail.SmtpServer points to "localhost" (or 127.0.0.1), make sure the SMTP service is running on port 25. Sometimes the problem arises due to relay issues.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
Sujith John Thomas, an accomplished technical architect specializing in Object-Oriented Design and Analysis with extensive experience in full cycle of software development.Expertise in Microsoft stack technologies such as C#,ASP.NET,Web Forms/MVC,WCF,Web Service,Web API,SQL Server etc. Also focusing on client side languages,libraries and frameworks like Javascript,jQuery,AngularJS etc.

Comments and Discussions

 
GeneralRe: cannot send email Pin
Sigurd Johansen25-Dec-05 9:10
Sigurd Johansen25-Dec-05 9:10 
GeneralRe: cannot send email Pin
renji_cj4-Apr-06 21:49
renji_cj4-Apr-06 21:49 
Questionhow to check SMTP server is alive Pin
tiwari piyush24-Nov-05 2:03
tiwari piyush24-Nov-05 2:03 
AnswerRe: how to check SMTP server is alive Pin
Sujith John Thomas1-Dec-05 18:46
Sujith John Thomas1-Dec-05 18:46 
GeneralRe: how to check SMTP server is alive Pin
mstehle2-Dec-05 3:57
mstehle2-Dec-05 3:57 
GeneralSmtpServer.Insert does nothing! Please read! Pin
mstehle23-Nov-05 9:15
mstehle23-Nov-05 9:15 
GeneralRe: SmtpServer.Insert does nothing! Please read! Pin
Sujith John Thomas1-Dec-05 19:27
Sujith John Thomas1-Dec-05 19:27 
GeneralRe: SmtpServer.Insert does nothing! Please read! Pin
mstehle2-Dec-05 3:57
mstehle2-Dec-05 3:57 
If you look at the value of SMTPServer after you call SMTPServer.Insert you will notice it is blank. What this tells System.Web.Mail is that you want to send mail via the local pickup directory ("C:\inetpub\mailroot\pickup\"). The underlying code in System.Web.Mail then attempts to write an EML file out to this directory.

When you specify a server name the underlying CDOSYS code in System.Web.Mail attempts to connect directly to the server you specify via port 25. The error your are getting means that you can't connect to the server named.

You can use the following KB article to manually test the server and port using TelNet...
http://support.microsoft.com/kb/q153119/[^]

If you can't connect via TelNet then you might have other problems going on. The SMTP Service might not be running or you may have anti-virus or firewall software blocking the port. Or you could simply have the wrong server name.

Also, keep in mind that you should never send via port on the local machine. It may work fine but you don't take advantage of the SMTP Service which manages the sending of mail put in the pickup directory.

Hope this helps clear things up a bit. Let me know if you have anymore questions...

Matt Stehle - Microsoft Developer Support Team, Messaging and Collaboration
http://blogs.msdn.com/mstehle/
GeneralGreat article Pin
LarryPiegza23-Nov-05 2:32
LarryPiegza23-Nov-05 2:32 
GeneralRe: Great article Pin
Sujith John Thomas1-Dec-05 18:10
Sujith John Thomas1-Dec-05 18:10 
GeneralMcAfee will also stop emails from going out... Pin
fulano222-Nov-05 8:19
fulano222-Nov-05 8:19 
GeneralRe: McAfee will also stop emails from going out... Pin
Sujith John Thomas1-Dec-05 18:48
Sujith John Thomas1-Dec-05 18:48 
GeneralRe: McAfee will also stop emails from going out... Pin
Amit Sanandiya From Morbi30-Mar-12 18:01
Amit Sanandiya From Morbi30-Mar-12 18:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.