In this article I will explain with an example, how to create a Contact Us Page in ASP.Net using C# and VB.Net.
The Contact Us Form contains some TextBox controls and a FileUpload control to attach file.
When the Send Button is clicked, the values from the TextBox fields are embedded into HTML string and the HTML string is send as Email and the File is attached to the Email.
HTML Markup
The HTML Markup consists of TextBox fields, RequiredField validators, a Button and a Label.
There is a Custom Validator applied for validation to the Body Multiline TextBox.
<table border="0">
<tr>
<td>Name:</td>
<td><asp:TextBox ID="txtName" runat="server"/></td>
<td><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="required" ControlToValidate="txtName"/></td>
</tr>
<tr>
<td>Subject:</td>
<td><asp:TextBox ID="txtSubject" runat="server"></asp:TextBox></td>
<td><asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="required"
ControlToValidate="txtSubject"/></td>
</tr>
<tr>
<td>Email:</td>
<td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
<td>
<asp:RegularExpressionValidatorID="valRegEx" runat="server" ControlToValidate="txtEmail"
ValidationExpression=".*@.*\..*" ErrorMessage="*Invalid Email address." Display="dynamic"/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="required"
ControlToValidate="txtEmail"/>
</td>
</tr>
<tr>
<td valign="top">Body:</td>
<td><asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine"/></td>
<td valign="top"><asp:CustomValidator ID="CustomValidator1" ClientValidationFunction = "ValidateTinyMCE" runat="server" ErrorMessage="required"></asp:CustomValidator></td>
</tr>
<tr>
<td></td>
<td><asp:FileUpload ID="FileUpload1" runat="server"/></td>
<td></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnSend" runat="server" Text="Send" OnClick="Send"/></td>
<td></td>
</tr>
<tr>
<td></td>
<td><asp:Label ID="lblMessage" runat="server" Text="" ForeColor="Green"/></td>
</tr>
</table>
Applying the TinyMCE Plugin to the TextBox
Inside the Init event handler of the TinyMCE plugin, the plugin is applied to the TextArea element i.e. Multiline TextBox.
<script type="text/javascript" src="https://tinymce.cachefly.net/4.0/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({ selector: 'textarea', width: 300 });
</script>
Validating the TinyMCE TextBox
Following is the JavaScript Validation function for the Custom Validator for the Multiline TextBox to which the TinyMCE plugin is applied.
<script type = "text/javascript">
function ValidateTinyMCE(sender, args) {
var isValid = true;
var txtBody = tinyMCE.get('<%=txtBody.ClientID%>');
if (txtBody.getContent() == "") {
isValid = false;
}
else {
//Check for space tag.
if (txtBody.getContent() == "<p> </p>") {
//Clear TinyMCE.
txtBody.execCommand('mceSetContent', false, "");
isValid = false;
}
}
args.IsValid = isValid;
}
</script>
Mail Server Settings in Web.Config file
Following are the Mail Server settings in the Web.Config file.
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="sender@gmail.com">
<network
host="smtp.gmail.com"
port="587"
enableSsl="true"
userName="sender@gmail.com"
password="SenderGmailPassword"
defaultCredentials="true"/>
</smtp>
</mailSettings>
</system.net>
MailMessage Class Properties
Following are the required properties of the MailMessage class.
From – Sender’s email address.
To – Recipient(s) Email Address.
CC – Carbon Copies. (If any)
BCC – Blind Carbon Copies. (If any)
Subject – Subject of the Email.
Body – Body of the Email.
IsBodyHtml – Specify whether body contains text or HTML mark up.
Attachments – Attachments. (If any)
ReplyTo – ReplyTo Email address.
SMTP Class Properties
Following are the properties of the SMTP class.
Host – SMTP Server URL. (Gmail: smtp.gmail.com)
EnableSsl – Specify whether your host accepts SSL Connections. (Gmail: True)
UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of the Account used to send emails.
Credentials – Valid login credentials for the SMTP server. (Gmail: email address and password)
Port – Port Number of the SMTP server. (Gmail: 587)
Namespaces
You will need to import the following namespaces.
C#
using System.Net;
using System.Net.Mail;
using System.Net.Configuration;
VB.Net
Imports System.Net
Imports System.Net.Mail
Imports System.Net.Configuration
Sending HTML Email using Contact Us Form in ASP.Net
When the Send Button is clicked, the Sender email address (from) is fetched from the SmtpSection of the Web.Config file, the Subject and Body are fetched from their respective TextBoxes in the Contact Us Form and all these values are set into an object of the MailMessage class.
Then an object of the SmtpClient class is created and the settings of the Mail Server such has Host, Port, DefaultCredentials, EnableSsl, Username and Password are fetched from the mailSettings section of the Web.Config file and attached to the SmtpClient class object.
Finally, a Success message is set in the Label control.
C#
protected void Send(object sender, EventArgs e)
{
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
using (MailMessage mm = new MailMessage(smtpSection.From, "admin@aspsnippets.com"))
{
mm.Subject = txtSubject.Text.Trim();
mm.Body = "Name: " + txtName.Text + "<br /><br />Email: " + txtEmail.Text + "<br />" + txtBody.Text;
mm.IsBodyHtml = true;
if (FileUpload1.HasFile)
{
string fileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
mm.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, fileName));
}
SmtpClient smtp = new SmtpClient();
smtp.Host = smtpSection.Network.Host;
smtp.EnableSsl = smtpSection.Network.EnableSsl;
NetworkCredential networkCred = new NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials;
smtp.Credentials = networkCred;
smtp.Port = smtpSection.Network.Port;
smtp.Send(mm);
}
lblMessage.Text = "Email sent sucessfully.";
}
VB.Net
Protected Sub Send(ByVal sender As Object, ByVal e As EventArgs)
Dim smtpSection As SmtpSection = CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"), SmtpSection)
Dim mm As MailMessage = New MailMessage(smtpSection.From, "admin@aspsnippets.com")
mm.Subject = txtSubject.Text.Trim
mm.Body = "Name: " & txtName.Text & "<br /><br />Email: " & txtEmail.Text & "<br />" & txtBody.Text
mm.IsBodyHtml = True
If FileUpload1.HasFile Then
Dim fileName As String = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName)
mm.Attachments.Add(New Attachment(FileUpload1.PostedFile.InputStream, fileName))
End If
Dim smtp As SmtpClient = New SmtpClient
smtp.Host = smtpSection.Network.Host
smtp.EnableSsl = smtpSection.Network.EnableSsl
Dim networkCred As NetworkCredential = New NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password)
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials
smtp.Credentials = networkCred
smtp.Port = smtpSection.Network.Port
smtp.Send(mm)
lblMessage.Text = "Email sent sucessfully."
End Sub
Possible Errors
Errors when submitting TinyMCE editor Rich Text HTML content
Server Error in 'ASP.Net' Application.
A potentially dangerous Request.Form value was detected from the client (txtBody"=<p>Hello</p>").
Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case.
Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (txtBody="<p>Hello</p>").
Solution
Errors while sending Email using Gmail
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
Solution
Screenshots
The Contact Us Form
The received email
Downloads