In this article I will explain with an example, how to create a Contact Us Form with HTML
RichTextEditor in ASP.Net using C# and VB.Net.
Mail Server Settings in Web.Config file
The following Mail Server settings need to be saved in the Web.Config file.
Note: It is necessary to use the sender’s email address credentials while defining the Gmail SMTP Server Credentials as Gmail the sender’s email address must be same as the Gmail Username specified in credentials.
<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>
HTML Markup
The following HTML Markup consists of:
TextBox – For capturing the values of Name, Subject, Email address and Body.
The TextBox for capturing Body of the Email has been assigned with the
TextMode property set to
MultiLine which will be made a Rich TextBox Editor using the
TinyMCE RichTextEditor plugin.
CustomValidator – For validating if Body Multiline TextBox has content or not.
Events
ClientValidationFunction – For calling
ValidateTinyMCE JavaScript function.
FileUpload – For attaching file as attachment to the email.
Button – For sending email.
The Button has been assigned with an OnClick event handler.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Name:</td>
<td><asp:TextBox ID="txtName" runat="server" /></td>
<td><asp:RequiredFieldValidator ID="rfvName" 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="rfvSubject" runat="server" ErrorMessage="required"
ControlToValidate="txtSubject" /></td>
</tr>
<tr>
<td>Email:</td>
<td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
<td>
<asp:RegularExpressionValidator ID="revEmail" runat="server" ControlToValidate="txtEmail"
ValidationExpression=".*@.*\..*" ErrorMessage="*Invalid Email address." Display="dynamic" />
<asp:RequiredFieldValidator ID="rfvEmail" 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="cvBody" ClientValidationFunction="ValidateTinyMCE" runat="server" ErrorMessage="required"></asp:CustomValidator></td>
</tr>
<tr>
<td></td>
<td><asp:FileUpload ID="fuAttachment" runat="server" /></td>
<td></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnSend" runat="server" Text="Send" OnClick="Send" /></td>
<td></td>
</tr>
</table>
Applying the TinyMCE Plugin to the Multiline TextBox
TinyMCE plugin implementation
Inside the HTML, the following
TinyMCE JS file is inherited.
1. tinymce.min.js
Inside the
Init event handler of the
TinyMCE plugin, the plugin is applied to the TextArea element i.e.
Multiline TextBox
Note: The ASP.Net Multiline TextBox is rendered as TextArea element in HTML, hence the
TinyMCE plugin has been applied to TextArea element.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.0.20/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({ selector: 'textarea', width: 300 });
</script>
Validating the TinyMCE TextBox
When
Send button is clicked, the ValidateTinyMCE
JavaScript function of the CustomValidator is called.
<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>
Namespaces
You will need to import the following namespaces.
C#
using System.Net;
using System.Net.Mail;
using System.IO;
using System.Configuration;
using System.Net.Configuration;
VB.Net
Imports System.Net
Imports System.Net.Mail
Imports System.IO
Imports System.Configuration
Imports System.Net.Configuration
Sending Email using Gmail SMTP
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)
Sending Contact Us Form details in Mail
When the Send Button is clicked, the Sender email address (from) is fetched from the SMTP section of the Web.Config file, the values of Name, Subject, Email and Body are fetched from their respective TextBoxes and all these values are set into an object of the MailMessage class.
Attaching File
The FileUpload is checked for Attachment and if it has File then the posted File is added as Attachment to the MailMessage object.
Sending Email
Then, an object of the SmtpClient class is created and the values of Host, Port, DefaultCredentials, EnableSsl, Username and Password are fetched from the SMTP section of the Web.Config file and are set in respective properties of the SmtpClient class object.
Finally, the email is being sent using the Send function of the SmtpClient class object and a success message is displayed in JavaScript Alert Message Box using RegisterStartupScript method.
C#
protected void Send(object sender, EventArgs e)
{
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
using (MailMessage mm = new MailMessage(smtpSection.From, "recipient@aspsnippets.com"))
{
mm.Subject = txtSubject.Text.Trim();
mm.Body = "Name: " + txtName.Text + "<br /><br />Email: " + txtEmail.Text + "<br />" + txtBody.Text;
mm.IsBodyHtml = true;
if (fuAttachment.HasFile)
{
string fileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, fileName));
}
using (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);
}
}
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Email sent.');", true);
}
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, "recipient@aspsnippets.com")
mm.Subject = txtSubject.Text.Trim
mm.Body = "Name: " & txtName.Text & "<br /><br />Email: " & txtEmail.Text & "<br />" & txtBody.Text
mm.IsBodyHtml = True
If fuAttachment.HasFile Then
Dim fileName As String = Path.GetFileName(fuAttachment.PostedFile.FileName)
mm.Attachments.Add(New Attachment(fuAttachment.PostedFile.InputStream, fileName))
End If
Using 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)
End Using
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Email sent.');", True)
End Sub
Possible Errors
1. Errors when submitting TinyMCE editor Rich Text HTML content
The following error occurs when you try to submit HTML content to server.
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
2. Errors while sending Email using Gmail
The following error occurs when you try to send email using Gmail credentials in your application.
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