Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » ASP.NET 2.0/3.5 » Sending email in ASP.NET 2.0

Sending email in ASP.NET 2.0

This article will help you to learn sending email in ASP.NET 2.0. It is also describes how ASP.NET 2.0 is different from its previous version for sending email.

Author Rank :
Page Views : 15754
Downloads : 432
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
SendEmail.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction:

The System.Net.Mail namespace in ASP.NET 2.0 has replaced the System.Web.Mail namespace in ASP.NET 1.x. In ASP.NET 2.0, you should know that the method of sending emails has changed slightly. Follow Brad Kingsley as he sends his first email from an ASP.NET 2.0 application.

Changes to send message in ASP.NET 20 and its previous version

  • System.Net.Mail.SmtpClient is used instead of System.Web.Mail.SmtpMail.
  • System.Net.MailMessage Class is used instead of System.Web.Mail.MailMessage. 
  • The System.Net.MailMessage class collects from address as MailAddress object.
  • The System.Net.MailMessage class collects To, CC, Bcc addresses as MailAddressCollection.
  • MailMessage Body Format is replaced by IsBodyHtml. 

In the given example the form contains five textboxes: 

  • First textbox is used for recipient's email address. 
  • Second textbox is used for sender's email address.
  • Third textbox is used for subject of the email.
  • Fourth textbox is used for the body of the email.
  • Fifth textbox is used for the list status (it provide the message that mail has sent or not).

One button is used for sending the email. So we write the code on the button's click event.

 

We add the System.Net.Mail namespace for sending the email.

 

For Example: Through this example you can understand how to send the email in ASP.NET 2.0.

 

These are the following steps to help you to send email in ASP.NET 2.0.

 

Step 1: Open your new website.

Step 2: Design the page.

Step 3: Now add the System.Net.Mail namespace.

Step 4: Write the cs code on the button's click event.  

 

Default.aspx:

 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Email sending</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <table cellpadding="10" cellspacing="0" border="2" width="40%" height="100px">

        <tr>

        <td valign="top" style="padding-top:20px; background-color: #ffccff;">

        <asp:Label ID="Label1" runat="server" Text="To " ForeColor="Purple">     </asp:Label> &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;

        <asp:TextBox ID="T1" runat="server" BackColor="#C0FFFF"></asp:TextBox>

        <br /><br />

        <asp:Label ID="Label2" runat="server" Text="From" ForeColor="Purple">  </asp:Label>&nbsp; &nbsp;

        <asp:TextBox ID="T2" runat="server" BackColor="#C0FFFF"></asp:TextBox><br /><br />

        <asp:Label ID="Label3" runat="server" Text="Subject" ForeColor="Purple"></asp:Label>

        <asp:TextBox ID="T3" runat="server" BackColor="#C0FFFF"></asp:TextBox><br /><br />

        <asp:Label ID="Label4" runat="server" Text="Body" ForeColor="Purple"></asp:Label>&nbsp; &nbsp;

        <asp:TextBox ID="T4" runat="server" Height="100px" Width="200px" BackColor="#C0FFFF" ForeColor="Black"></asp:TextBox><br /><br />

        <asp:Label ID="Label5" runat="server" Text="List Status" ForeColor="Purple"></asp:Label>

        <asp:TextBox ID="T5" runat="server" BackColor="#C0FFFF" ForeColor="Red"></asp:TextBox><br/><br />

        <asp:Button ID="Send" runat="server" Text="Send" OnClick="Send_Click" BackColor="#C0C000" ForeColor="Navy" />

        </td>

       </tr>

     </table></div>

   </form>

</body>

</html>

 

Design view of the above page is as follows:

 

 

 

Figure 1: Design of the form.

 

Default.aspx.cs:

 

using System;

using System.Data;

using System.Configuration;

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.Mail;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {}

    protected void Send_Click(object sender, EventArgs e)

    {

        SmtpClient smtpclient = new SmtpClient();

        MailMessage message = new MailMessage();

        smtpclientl.Host = "localhost";

        try

        {

            MailAddress SendFrom = new MailAddress(T1.Text);

            MailAddress SendTo = new MailAddress(T2.Text);

            MailMessage MyMessage = new MailMessage(SendFrom, SendTo);

            MyMessage.Subject = T3.Text;

            MyMessage.Body =T4.Text;

            T5.Text = "Message Sent";

        }

        catch (Exception ex)

        {

            T5.Text = ex.ToString();

        }

    }

}

 

Output: The following page will display when you debug this code. And you should fill the given entries in the form.

 

 

 

Figure 2: After debug the code this page will open.

 

After filling all entries click on send button then you will see the following output.

  

 

 

Figure 3: This figure represents the final output.

 

List status gives the information about the sending message.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Purushottam Rathore

I am working as a Software Developer and has 4 years of experience on Microsoft Technology and having a Master Degree in Computer Application. I really like to work in the .NET platform. and working with ASP.NET 2.0/3.5, Web Services, WPF, WCF, Silverlight, AJAX, JavaScript, JQuery, Ado.net, MsAccess, SQL Server 2005/2008.

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Gauge for SharePoint
Become a Sponsor
 Comments
I am not able to send mail with this code by kim On February 7, 2008
Hi, i tried same cod ebut still i ma not able to sen dmail can u please let me know the possible reason? Kim
Reply | Email | Modify 
Re: I am not able to send mail with this code by Purushottam On February 21, 2008

hi

Write this code and run ur application.

Default.aspx

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Send Email</title>

</head>

<body>

    <form id="form1" runat="server">

        <table width="80%" align="center" border="1" cellpadding="0" cellspacing="0">

            <tr>

                <td width="20%">

                    <h4>Send Email</h4>

                </td>

                <td align="left">

                    <asp:Label ID="lblError" runat="server" Visible="false"></asp:Label></td>

            </tr>

            <tr>

                <td colspan="2">

                    <table id="tblEmail" align="center" runat="server" cellpadding="0" cellspacing="0"

                        width="90%">

                        <tr>

                            <td width="20%" align="right">

                                <asp:Label ID="lblEmail" runat="server" Text="To:"></asp:Label>

                            </td>

                            <td align="left" width="90%" style="height: 24px">

                                <asp:TextBox ID="txtemail" Width="50%" runat="server"></asp:TextBox>

                            </td>

                        </tr>

                        <tr height="10px">

                            <td colspan="2">

                            </td>

                        </tr>

                        <tr>

                            <td width="20%" align="right">

                                <asp:Label ID="lblFrom" runat="server" Text="From:"></asp:Label>

                            </td>

                            <td align="left">

                                <asp:TextBox ID="txtFrom" Width="50%" runat="server"></asp:TextBox>

                            </td>

                        </tr>

                        <tr height="10px">

                            <td colspan="2">

                            </td>

                        </tr>

                        <tr>

                            <td width="20%" align="right" style="height: 24px">

                                <asp:Label ID="lblsubject" runat="server" Text="Subject:"></asp:Label>

                                <asp:Label ID="lblredstar" runat="server" Text="*"></asp:Label>

                            </td>

                            <td align="left" style="height: 24px">

                                <asp:TextBox ID="txtsubject" Width="50%" runat="server"></asp:TextBox>

                            </td>

                        </tr>

                        <tr height="10px">

                            <td colspan="2">

                            </td>

                        </tr>

                        <tr>

                            <td width="20%" align="right" valign="top">

                                <asp:Label ID="lblmessage" runat="server" Text="Your Message:"></asp:Label>

                                <asp:Label ID="lblstar2" runat="server" Text="*"></asp:Label>

                            </td>

                            <td align="left">

                                <asp:TextBox ID="txtMessage" runat="server" Height="200px" Width="70%" TextMode="MultiLine"></asp:TextBox></td>

                        </tr>

                        <tr height="10px">

                            <td colspan="2">

                            </td>

                        </tr>

                        <tr height="10px">

                            <td style="height: 10px">

                            </td>

                            <td align="left" style="height: 10px">

                                <asp:Button ID="btnsendEmail" runat="server" Text="Send Email" OnClick="btnSendEmail_Click" />

                            </td>

                        </tr>

                        <tr height="20px">

                            <td colspan="2" style="height: 20px">

                            </td>

                        </tr>

                    </table>

                </td>

            </tr>

        </table>

    </form>

</body>

</html>

 

Default.aspx.cs:

 

using System;

using System.Data;

using System.Configuration;

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.Mail;

 

public partial class _Default : System.Web.UI.Page

{

    protected void btnSendEmail_Click(object sender, EventArgs e)

    {

        if (txtMessage.Text == "")

        {

            lblError.Visible = true;

            lblError.Text = "Please write your message to user.";

        }

        else

        {

            sendMessage();

            txtMessage.Text = "";

        }

    }

 

    private void sendMessage()

    {

        SmtpClient smtpClient = new SmtpClient();

        MailMessage mailMessage = new MailMessage();

        try

        {

            MailAddress fromAddress = new MailAddress(txtFrom.Text);

            mailMessage.From = fromAddress;

            string MailTo = txtemail.Text;

            mailMessage.To.Add(MailTo);

            mailMessage.Subject = txtsubject.Text;

 

            string BodyStr = "";

            BodyStr += '\n' + "Email: " + txtFrom.Text;

            BodyStr += '\n' + "Subject: " + txtsubject.Text;

            BodyStr += '\n' + "MessageBody: " + txtMessage.Text;

            mailMessage.Body = BodyStr;

            smtpClient.Host = "localHost";

            smtpClient.Send(mailMessage);

            lblError.Visible = true;

            lblError.Text = "Your mail has been sent successfully";

            tblEmail.Visible = false;

        }

        catch

        {

            lblError.Visible = true;

            lblError.Text = "There has been some error, please try again.";

        }

    }

 

}

 

 

Reply | Email | Modify 
Re: Re: I am not able to send mail with this code by sara On February 21, 2008

Hi

should i test the above code on IIS  such that it sends email to the corresponding Email id  or does it work if I just run the asp.net application.

Thanks

 

Reply | Email | Modify 
Re: Re: Re: I am not able to send mail with this code by Purushottam On September 22, 2008

Hi

First You should Configure SMTP server. After that you can send mail through this code.

Good Luck.

Reply | Email | Modify 
I like it by chandara On February 11, 2009
I understand your source code. But I want to design program could send mail from pc to email on server. It means I enter my friend's emaill address and I write message and then I click on send button. My mail is sent to my friend's input. For example, gmail.com, hotmail.com, yahoo.com. Thanks
Reply | Email | Modify 
Re: I like it by Purushottam On February 11, 2009
Thanks chandara You have to Configure SMTP server After that you can send send mail from pc to on server.
Reply | Email | Modify 
Smtp sever by shamjith On September 23, 2010
Hello sir,

Please tel me the steps for configuring SMTP server in windows XP
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.