Click here to Skip to main content
Click here to Skip to main content

SMTP Mail System Using ASP.NET 2.0

, 16 Jul 2007
Rate this:
Please Sign up or sign in to vote.
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:

//----------------------------------------------------------
//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

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:

<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)

About the Author

Sujith John Thomas
Team Leader
India India
Sujith John Thomas, an accomplished Software Engineer specializing in Object-Oriented Design and Analysis with extensive experience in full cycle of software development,having good exposure in C#,ASP.NET,XML,AJAX,Web Service,Java Script and SQL Server .Currently developing web applications and windows applications in .NET 2.0/3.5 framework.

Comments and Discussions

 
QuestionHOW TO READ A MAIL FILE(EML) FROM SERVER PinmemberDeepakharsora25-Sep-08 20:34 
Generalport 25 PinmemberCroatia_my24-Nov-07 10:13 
GeneralRe: port 25 PinmemberSujith John Thomas30-Nov-07 17:04 
Questioncan not get port no from web.config Pinmemberalay10122-Nov-07 8:03 
AnswerRe: can not get port no from web.config PinmemberSujith John Thomas22-Nov-07 9:57 
QuestionHave any doubts? PinmemberSujith John Thomas16-Jul-07 1:30 
AnswerRe: Have any doubts? Pinmembersneha Bhattacharjee20-Jul-07 7:19 
AnswerRe: Have any doubts? [modified] PinmemberSujith John Thomas21-Jul-07 1:06 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 16 Jul 2007
Article Copyright 2007 by Sujith John Thomas
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid