ASP.NET Web Pages – Sending Email

To send email in ASP.NET Web Pages we use the WebMail Class. This class contains all the methods and properties available to send email.

  1. Create a new empty website from the template gallery and name it SendingEmail
  2. In the root directory create an _AppStart.cshtml file and insert the following:
WebMail.SmtpServer = "smtp.gmail.com";
WebMail.EnableSsl = true;
WebMail.UserName = "Your username";
WebMail.Password = "password";
WebMail.From = "[email protected]";

Here we will use Google Mail to send our email. Google will only accept secure connections, so SSL must be set to true. The WebMail.From is usually your login username. Another setting which you might like to specify is the WebMail.SmtpPort. We have not done it here as it can cause errors, but you may need it.

In the Default.cshtml we will create a small form like we did in the forms tutorial. Let’s begin with creating our variables and then set up validation. For this form we will collect the user’s full name, email address and comment.

@{

var FullName  = "";
var Email = "";
var Comment = "";

Validation.Add("FullName",
Validator.Required()
);

Validation.Add("Email",
Validator.Required(),
Validator.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", "Please enter a correct email address format")
);

Validation.Add("Comment",
Validator.Required(),
Validator.StringLength(500, 10)
);

Here we created three variables and setup validation. The email address uses a regex to make sure the data entered is a correct email address. The Validation.Required() method does not need an argument, because a default value will kick in saying “This field is required”.

Now we will process the data on post:

if (IsPost)
{

    FullName = Request["FullName"];
    Email = Request["Email"];
    Comment = Request["Comment"];

    var emailMessage = FullName + " " + "has contacted you from your website their email address is: " + Email + " " + "and message is: " + Comment;

    if (Validation.IsValid())
    {
     try
    {

        WebMail.Send("[email protected]", "A user has contacted you", emailMessage);
        Response.Write("Message Sent!");

    }catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
    }else{
       Validation.AddFormError("Sorry something went wrong there.");
    }
}
}

When the data is submitted we get the values from the HTML elements, and a new local variable called emailMessage is created. This simply joins the user data with a simple message we will use to send to the email address. We then make sure the data is valid and send the email. When sending an email it is good practice to put it in a try catch block as errors can occur.

HTML

For the sake of brevity the full HTML document markup has been omitted.

<form method="post">
@Html.ValidationSummary(true)
 
<div>
 <label>Full Name</label>
 <input type="text" name="FullName"/>
 @Html.ValidationMessage("FullName")
</div>
 
<div>
 <label>Email</label>
 <input type="text" name="Email"/>
 @Html.ValidationMessage("Email") 
</div>
 
<div>
  <label>Comment</label>
  <textarea name="Comment"></textarea>
  @Html.ValidationMessage("Comment") 
</div>
 
<input type="submit"/>
        
</form>

Here we could have used type=”email” but we wanted to demonstrate the validation working. Bring up the website and fill in the fields. For the first try, fill everything in correctly and for second attempt don’t.

Preserve User Submitted Data

Here you will notice that on the second attempt the data the user enters has disappeared. We can solve this issue quite easily by specifying the value attribute for the HTML elements alongside the correct variable like this:

<input type="text" value="@FullName" name="FullName"/>
<input type="text" value="@Email" name="Email"/>
<textarea name="Comment">@Comment</textarea>

However, this will only work if the variables are global (they’re declared outside of the If Statement). If the variables are created inside the If Statement then they are local and you will get an error saying “X is not declared” (X = the variable). If you wish to create the variables inside the If Statement you can do this to preserve the data:

<input type="text" value="@Request["FullName"]" name="FullName"/>

Summary

This tutorial covered how to send email and how to validate the user input before sending email, as well as how to retain user data on form submit. For more information about the WebMail class please see the reference.