Email Delivery with ASP.NET User Controls

ASP.NET provide solid base for code reuse in various ways, user controls are one of them. User control provide good platform to build functionality that can be shared across multiple pages within a website project, this increases code reusability and rapid application development because developer has to design and develop them only once in a project and they can use it anywhere they need to provide similar functionality. This makes it extremely easy to maintain the code because there will be only one place where developer will have to go and modify the code and once that code is modified changes get reflected wherever that control is used.

Sending email form is one of the most common feature build for a website, and it needs to be included in many places like if you have a contact us page or you have a page where user can report issues they are getting. Developing email form involve many steps to develop so it is a good candidate to be converted to an user control for email and then use it anywhere you like.

ASP.NET provides similar environment to develop user control page (.ascx extension) as it does for web form page (.aspx extension). It has full visual designer support so you can design your control visually. Both aspx and ascx pages inherit from TemplateControl class so they share a lot in common like events, properties etc, and follow same life cycle so you will see page_load in aspx and will also find page_load in ascx page.

To build new user control add new item to your website project -> in Add New item dialog box select Web User Control -> give it name (for demo purposes I am going to leave it to the default name)

You will notice difference between web page and user control on the very first line of your newly created user control file. In web page you get <%@ Page %> directive and in user control you get <%@ Control %> directive.

Let's start adding server controls like label, textboxes to the page to build your user control.

Server controls we are going to add are:

  1. Fieldset to define area and nice border along with a legend tag
  2. Within legend tag we will put a Literal control because we need to expose legend text as a property so that we can modify it according to the situation wherever we are using this user control
  3. For laying out server controls nicely on the page we will use html table with border 0, cell spacing 10, cell padding 0, 5 rows and 2 columns
  4. Then we will add controls to accept Name, Email, Subject and Message user inputs
  5. In the last row we will add two button controls, one for sending the email and other for resetting controls to blank

After setting user control layout your HTML markup code should look like this:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>

<fieldset>

<legend>

<asp:Literal Text="Contact Us" runat="server" ID="LegendText" /></legend>

<table border="0" cellpadding="10" cellspacing="10">

<tr>

<td>

Your Name:

</td>

<td>

<asp:TextBox runat="server" ID="txtUserName" Width="341px" />

</td>

</tr>

<tr>

<td>

Your Email:

</td>

<td>

<asp:TextBox runat="server" ID="txtUserEmail" Width="341px" />

</td>

</tr>

<tr>

<td>

Subject:

</td>

<td>

<asp:TextBox runat="server" ID="txtEmailSubject" Width="341px" />

</td>

</tr>

<tr>

<td>

Message:

</td>

<td>

<asp:TextBox runat="server" ID="txtEmailMessage" TextMode="MultiLine"

Columns="40" Rows="5" />

</td>

</tr>

<tr>

<td>

<asp:Button Text="Send" runat="server" ID="btnSendEmail"/>

</td>

<td>

<asp:Button Text="Reset" runat="server" ID="btnReset" />

</td>

</tr>

</table>

</fieldset>

 

Now we will open code behind file and create a property to expose it with the user control. Create a property of type string before Page_Load method, after adding property in code behind file of user control, your code should look like this:

public string LegendHeader

{

get

{

return LegendText.Text;

}

set

{

LegendText.Text = value;

}

}

 

protected void Page_Load(object sender, EventArgs e)

{

 

}

 

You can attach events to controls within user control same way as you can do it in web form.

So we will attach click event to our Send button and Reset button. In order to do this you can either double click on buttons by switching user control page to designer or add OnClick event from Markup of the page. We will use double click technique because it is easy and quick.

Now you should have two new methods in your code behind file:

protected void btnSendEmail_Click(object sender, EventArgs e)

{

 

}

protected void btnReset_Click(object sender, EventArgs e)

{

 

}

Let's start adding logic to send email to btnSendEmail_Click block :

In order to send email from this control, first you will have to add a reference of System.Net and System.Net.Mail in using section:

using System.Net.Mail;

using System.Net;

 

After this we need to create an object of MailMessage class and:

  1. Add from email address (this is going to be the email account from your SMTP server)
  2. Add To email address (also from your SMTP server in this case but you can use other email addresses too if you are not building Contact Us page instead you are building send email notification to others kind of senario)
  3. Add Subject line (in this case, this is coming from User who is using the page to contact us)
  4. Add email body
  5. Define if email is going to be HTML email or Text format email

Now we will add Create object of SmtpClient object

  1. Add Delivery method to Network
  2. Set user name and password using Network credentials class
  3. Set port on smtp object to 25 (if using you are using SSL then port will be 587)
  4. Set EnableSSL property to false in this case and true if you are using SSL
  5. Use smtp objects send method to pass your mail message object and send the email

After adding code of btnSendEmail should look like this:

protected void btnSendEmail_Click(object sender, EventArgs e)

{

MailMessage message = new MailMessage();

message.From = new MailAddress("Demo@Example.com","Demo Email");

message.To.Add(new MailAddress("Demo@Example.com"));

message.Subject = string.Format("Message from: {0}, {1}",txtUserName.Text,txtEmailSubject.Text);

SmtpClient smtp = new SmtpClient("mail.Example.com");

smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

smtp.Credentials = new NetworkCredential("Demo@Example.com", "password");

smtp.Port = 25;

smtp.EnableSsl = false;

message.IsBodyHtml=true;

message.Body = string.Format(@"This message is from <a mailto:'{0}'>{1}</a>. <hr />{2}",txtUserEmail.Text,txtUserName.Text,txtEmailMessage.Text);

smtp.Send(message);

}

In btnReset_Click block we will set all textboxes to blank:

protected void btnReset_Click(object sender, EventArgs e)

{

txtUserName.Text = "";

txtUserEmail.Text = "";

txtEmailSubject.Text = "";

txtEmailMessage.Text = "";

}

Once this is all setup your user control is ready to be used by web form pages.

Note: You cannot view user control directly in the browser, in order to see user control working you will have to add it to a ASPX page.

Lets add this control to a web page.

So to add your control to a web page, you will have to register your user control to the page first and you can do it in two ways:

  1. Open web form in Visual studio designer then drag and drop user control to the page
  2. Include <%@Register %> directive right after <%@Page %> directive and define src(location of the user control), tagname (name of the control), tagprefix (prefix that you are going to use like UC1 or ASP or anything else you like)

When you drop user control to the page visual studio automatically add <%@Register%> directive to the web page.

<%@ Register src="WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %>

 

Now if you have used markup to register your control, inside form tag if you start typing new tag intellisense should show you new user control and you can also set property that we defined in user control.

<uc1:WebUserControl ID="WebUserControl1" runat="server" LegendHeader="Email Contact Page" />

 

It's time to test new user control in browser:

 

Thank you.

Tags: , , ,

ASP.NET | Server Control