Click here to Skip to main content
15,886,362 members
Articles / Web Development / ASP.NET

SMTP Mail System Using ASP.NET 2.0

Rate me:
Please Sign up or sign in to vote.
1.22/5 (11 votes)
16 Jul 2007CPOL1 min read 42.2K   130   17   8
This article explores the mechanism of sending SMTP mail through the latest ASP.NET 2.0 technology, in a very simple manner.

Screenshot - mail2.jpg

Introduction

This article explores the mechanism of an SMTP mail system developed in the latest ASP.NET 2.0 technology. The readers will get a fairly good idea about the mail sending system and can easily develop a good mail service on their own. I have already posted an article about the mail sending mechanism using ASP.NET 1.1 technology which describes all the SMTP concepts, configuration, and development.

If you are really interested and want to know more about the concepts and configuration, you can very well refer to my previous article: Email System Using ASP.NET.

Background

SMTP stands for Simple Mail Transfer Protocol. Mails are sent using this perfect protocol. The .NET Framework supplies the SMTP namespace that enables you to send simple /complex mail messages. You can do advanced SMTP mail programming by utilizing the classes in the SMTP namespace.

Code Snippets

Here is the code for sending a mail:

C#
//----------------------------------------------------------
//Method to send the mail.
//----------------------------------------------------------
private void Send()
{ 
    //Assigning value to the variables
    _mTo = txtTo.Text.Trim();
    _mFrom =txtFrom.Text.Trim();
    _mSubject = txtSubject.Text.Trim();
    _mMessage = txtBody.Text.Trim();

    //Getting the mail server ip from the web.config file
    _mMailServer = 
      ConfigurationManager.AppSettings["MailServer"].ToString();
    //Getting the mail server port from the web.config file.
    _mPort = Int32.Parse(
      ConfigurationManager.AppSettings["MailServerPort"].ToString());

    try
    { 

        //Passing parameters to the Mail Message object.
        objMessage = new MailMessage(_mFrom, _mTo, _mSubject, _mMessage);
        //Instantiating Attachement object
        Attachment attach = new Attachment(fileAttach.PostedFile.FileName);
        //Adding attachment to the message.
        objMessage.Attachments.Add(attach);
        //Instantiating the SmtpClient
        SmtpClient objSmtpClient = new SmtpClient(_mMailServer, _mPort);
        //Setting default credentials to true
        objSmtpClient.UseDefaultCredentials = true;

        //Sending the mail. 
        objSmtpClient.Send(objMessage);
        Message("Mail has been sent successfully.");
        //Resetting the form
        Clear();
    }
    catch (FormatException ex)
    {
        Message("Format Exception:" + ex.Message);
    }
    catch (SmtpException ex)
    {
        Message("SMTP Exception:" + ex.Message);
    }
    catch (Exception ex)
    {
        Message("General Exception:" + ex.Message);
    }
}

Final solution

C#
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Mail;

public partial class SendMail : System.Web.UI.Page
{
#region DECLARATIONS
    private string _mMailServer;
    private string _mTo;
    private string _mFrom;
    private string _mMessage;
    private string _mSubject;
    private int _mPort;
    private MailMessage objMessage;
#endregion

#region EVENTS
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void btnSend_Click(object sender, EventArgs e)
    {
    Send();
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
    Clear();
    }
#endregion

#region METHODS
//----------------------------------------------------------
//Method to show the message 
//----------------------------------------------------------

    private void Message(string strMessage)
    {
        Label lblMsg = new Label();
        lblMsg.Text = strMessage;
        phMessage.Controls.Add(lblMsg);
    }

    //----------------------------------------------------------
    //Method to send the mail.
    //----------------------------------------------------------

    private void Send()
    { 
        //Assigning value to the variables
        _mTo = txtTo.Text.Trim();
        _mFrom =txtFrom.Text.Trim();
        _mSubject = txtSubject.Text.Trim();
        _mMessage = txtBody.Text.Trim();
        //Getting the mail server ip from the web.config file
        _mMailServer = 
          ConfigurationManager.AppSettings["MailServer"].ToString();
        //Getting the mail server port from the web.config file.
        _mPort = Int32.Parse(
          ConfigurationManager.AppSettings["MailServerPort"].ToString());

        try
        { 
            //Passing parameters to the Mail Message object.
            objMessage = new MailMessage(_mFrom, _mTo, _mSubject, _mMessage);
            //Instantiating Attachement object
            Attachment attach = new Attachment(fileAttach.PostedFile.FileName);
            //Adding attachment to the message.
            objMessage.Attachments.Add(attach);
            //Instantiating the SmtpClient
            SmtpClient objSmtpClient = new SmtpClient(_mMailServer, _mPort);
            //Setting default credentials to true
            objSmtpClient.UseDefaultCredentials = true;

            //Sending the mail. 
            objSmtpClient.Send(objMessage);
            Message("Mail has been sent successfully.");

            //Resetting the form
            Clear();
        }
        catch (FormatException ex)
        {
            Message("Format Exception:" + ex.Message);
        }
        catch (SmtpException ex)
        {
            Message("SMTP Exception:" + ex.Message);
        }
        catch (Exception ex)
        {
            Message("General Exception:" + ex.Message);
        }
    }

    //---------------------------------------------------------
    //Method for clearing the fields.
    //---------------------------------------------------------
    private void Clear()
    {
        txtTo.Text = string.Empty;
        txtFrom.Text = string.Empty;
        txtSubject.Text = string.Empty;
        txtBody.Text = string.Empty;
    }
#endregion
}

You have to do some configuration settings in order to make this work. Provide the IP address of the mail server and the port which you are using for sending mail in the appsettings section of the web.config file, as shown below:

XML
<configuration>
    <appSettings>
        <!--Mail System Specifications-->
        <!--Your Company Mail Server IP-->
        <!--For eg: 66.132.247.24 is my server ip-->
        <add key="MailServer" value=""/>
        <!--Port For Mail System-->
        <!--For eg: 25 is my server port-->
        <add key="MailServerPort" value=""/>
    </appSettings>
</configuration/>

Using the Solution

Download the source code files given above in the zip file and copy the contents into any directory.

Go to Internet Information Services (IIS) and create a virtual directory named SMTPMail and map the physical path to the virtual directory. Do the mail server configuration settings as mentioned above, in the web.config file.

The URL to use will be http://localhost/SMTPMail/. Happy coding..!!!

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

 
QuestionHOW TO READ A MAIL FILE(EML) FROM SERVER Pin
Deepakharsora25-Sep-08 20:34
Deepakharsora25-Sep-08 20:34 
Generalport 25 Pin
Croatia_my24-Nov-07 10:13
Croatia_my24-Nov-07 10:13 
GeneralRe: port 25 Pin
Sujith John Thomas30-Nov-07 17:04
Sujith John Thomas30-Nov-07 17:04 
You have to use your own smtp mail server port no.Port 25 might not work in all the cases.Please check with your system administrator.
Questioncan not get port no from web.config Pin
alay10122-Nov-07 8:03
alay10122-Nov-07 8:03 
AnswerRe: can not get port no from web.config Pin
Sujith John Thomas22-Nov-07 9:57
Sujith John Thomas22-Nov-07 9:57 
QuestionHave any doubts? Pin
Sujith John Thomas16-Jul-07 1:30
Sujith John Thomas16-Jul-07 1:30 
AnswerRe: Have any doubts? Pin
sneha Bhattacharjee20-Jul-07 7:19
sneha Bhattacharjee20-Jul-07 7:19 
AnswerRe: Have any doubts? [modified] Pin
Sujith John Thomas21-Jul-07 1:06
Sujith John Thomas21-Jul-07 1:06 

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.