Create A Contact Us Form For Your Website

Most of the time we have seen suggestion/complaint form in the footer of many websites but what if you want the same thing in your project?

Then I am here to guide you. As far as I know, there are two methods to implement this:

  1. Make a database and save the form details in that so that when the site admin logs in, he/she can see them.
  2. Generate an email from the code so you can get an email and can retrieve that on the go.

I will explain the second method here. This method will simply guide you on how to send an email and then you can use this in any way you like.

Building the Sample

Firstly, I created a form in HTML view of an MVC project which looks like the following.

Contact us

HTML for this form is.

@using(Html.BeginForm("email", "Home", FormMethod.Post)) {
    <div class="row">
        <div class="col-lg-12">
            <form name="sentMessage" id="contactForm" novalidate>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <input type="text" name="sname" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">
                            <p class="help-block text-danger"></p>
                        </div>
                        <div class="form-group">
                            <input type="email" name="semail" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">
                            <p class="help-block text-danger"></p>
                        </div>
                        <div class="form-group">
                            <input type="tel" name="sphone" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <textarea class="form-control" name="smessage" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="clearfix"></div>
                    <div class="col-lg-12 text-center">
                        <div id="success"></div>
                        <button type="submit" class="btn btn-xl" onclick="this.form.submit();">Send Message</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
}

If you copy and paste this HTML it won’t work as desired due to the CSS. So don’t get confused with the code this is just to guide you a bit, you can make any kind of form.

Observe the starting line of the HTML code I used.

@using(Html.BeginForm("email", "Home", FormMethod.Post))
{
    // Form content goes here
}

This is used to call the controller ActionResult method when the user submits this form. "email" is the name of the ActionResult method and "Home" is the controller. That is the main thing where the whole stuff happens.

In the controller, there is a method and an Action Method that calls the method.

public async Task<ActionResult> email(FormCollection form)
{
    var name = form["sname"];
    var email = form["semail"];
    var messages = form["smessage"];
    var phone = form["sphone"];
    var x = await SendEmail(name, email, messages, phone);
    if (x == "sent")
        ViewData["esent"] = "Your Message Has Been Sent";
    return RedirectToAction("Index");
}

private async Task<string> SendEmail(string name, string email, string messages, string phone)
{
    var message = new MailMessage();
    message.To.Add(new MailAddress("[email protected]")); // replace with receiver's email id
    message.From = new MailAddress("[email protected]"); // replace with sender's email id
    message.Subject = "Message From" + email;
    message.Body = "Name: " + name + "\nFrom: " + email + "\nPhone: " + phone + "\n" + messages;
    message.IsBodyHtml = true;
    using(var smtp = new SmtpClient())
    {
        var credential = new NetworkCredential
        {
            UserName = "[email protected]", // replace with sender's email id
            Password = "*****" // replace with password
        };
        smtp.Credentials = credential;
        smtp.Host = "smtp-mail.outlook.com";
        smtp.Port = 587;
        smtp.EnableSsl = true;
        await smtp.SendMailAsync(message);
        return "sent";
    }
}

So what's happening here is that I have created an async task of ActionResult type which is called when the user clicks the submit button and values from the form are passed into it.

public async Task<ActionResult> email(FormCollection form)

Async is used when you have to wait for an action to complete before moving ahead as this process requires some time so we need to use the async type and this allows us to use the await keyword in it.

private async Task<string> SendEmail(string name, string email, string messages, string phone)

This is a method that returns a string to tell the status. I have passed all the form values which I need in my email.

message.To.Add(new MailAddress("[email protected]")); // replace with receiver's email id

Here we have to write the email ID on which we want to receive the email.

message.From = new MailAddress("[email protected]"); // replace with sender's email id

Here are the senders' email id, I have used my ID in both so I am sending an email from one id to another which contains the users' query/suggestion, contact, name, and email, so I can respond later if I want to:

message.Subject = "Message From " + email;

Here goes the subject, I have written the user's email on the subject, you can write anything you like.

message.Body = "Name: " + name + "\n" +
               "From: " + email + "\n" +
               "Phone: " + phone + "\n" +
               messages;

Here goes the body, I have written the user's name, email, phone, and message in the body. You can get the desired things according to your requirements and form fields.

var credential = new NetworkCredential {
    UserName = "[email protected]", // replace with sender's email id     
    Password = "*****" // replace with password     
};   

// Here you have to give your email id and password of that id which you are using to send an email. 
// So our code can log in using these credentials.

smtp.Credentials = credential;
smtp.Host = "smtp-mail.outlook.com";
smtp.Port = 587;
smtp.EnableSsl = true;

These are the settings of the Hotmail /outlook email service. I was using my Hotmail ID as a sender and it worked. If you are using live/outlook/hotmail you can use these ones but for other clients, you can search Host and Port and replace these with those and it will work like a charm.

More Information

That's all folks, this is very easy to implement and I have tried my best to explain you step by step.

For more information, queries or to contact me kindly comment below.