Click here to Skip to main content
15,219,470 members

Building a Contact Form Using C#/ASP.NET MVC

Rate this:
4.81 (12 votes)
Please Sign up or sign in to vote.
4.81 (12 votes)
19 Oct 2016CPOL
This tip shows you how you can implement a contact form in C#/ASP.NET MVC


Through this tip, you will learn in a step by step manner to easily send email using System.Net.Mail.


This tip may be useful for intermediate developers who have some basics in C#, ASP.NET MVC, JQuery, JavaScript.

Using the Code

A) Operating Process

The first thing you need to know is how you can get the parameters of SMTP Server. The following links will help you to find them:

Examples of SMTP configuration:

  • Office365: Address:, Port: 587, SSL: true
  • Gmail: Address:, Port: 587, SSL: true
  • Yahoo: Address:, Port: 587, SSL: true

B) Source Code

1) Server Code

* ConfigurationSMTP class

public class ConfigurationSMTP
    //SMTP parameters
    public static string smtpAdress  = "";
    public static int    portNumber  = 587;
    public static bool   enableSSL   = true;
    //need it for the secured connection
    public static string from = "sender email";
    public static string password = "password of the above email";

* SendNewMessage method

This method contains the main code that sends a new message to a specific e-mail address.

How it works:

  1. Build a message (using MailMessage() class) thanks to data received from HTTP request such as: 'Destination Email', 'Subject', 'Message Body'.
  2. Create and configure the SMTP client using SmtpClient() class.
  3. Attach a credentials parameter when trying the creation of SMTP connection (using smtp.Credentials method).
  4. Send a message.
      public ActionResult SendNewMessage()
              Response.StatusCode = 200;
              //getting useful configuration
              string smtpAddress = ConfigurationSMTP.smtpAdress;
              //it can be a "" or whatever,
              //it depends on smtp server of your sender email.
              int portNumber = ConfigurationSMTP.portNumber;   //Smtp port
              bool enableSSL = ConfigurationSMTP.enableSSL;  //SSL enable

              string emailTo = Request.Params["to"];
              string subject = Request.Params["subject"];

              StringBuilder body = new StringBuilder();

              //building the body of our email
              body.Append("<html><head> </head><body>");
              body.Append("<div style=' font-family: Arial;
              font-size: 14px; color: black;'>Hi,<br><br>");
              //Mail signature
              body.Append(string.Format("<span style='font-size:11px;font-family:
              Arial;color:#40411E;'>{0} - {1} {2}</span><br>",
              body.Append(string.Format("<span style='font-size:11px;font-family:
              Arial;color:#40411E;'>Mail: <a href=\"mailto:{0}\">{0}</a>
              </span><br>", ConfigurationSMTP.from));
              body.Append(string.Format("<span style='font-size:11px;font-family:
              Arial;color:#40411E;'>Tel: {0}</span><br>",
              body.Append(string.Format("<span style='font-size:11px;font-family:
              Arial;'><a href=\"web site\">{0}</a>
              body.Append(string.Format("<span style='font-size:11px; font-family:
              Arial;color:#40411E;'>{0}</span><br>", MessageModel.details));
              body.Append( "</body></html>");

              using (MailMessage mail = new MailMessage())
                  mail.From = new MailAddress(ConfigurationSMTP.from);
                  //destination adress
                  mail.Subject = subject;
                  mail.Body = body.ToString();
                  //set to true, to specify that we are sending html text.
                  mail.IsBodyHtml = true;
                  // Can set to false, if you are sending pure text.

                  string localFileName = "~/Content/TestAttachement.txt";
                  //to send a file in attachment.
                  mail.Attachments.Add(new Attachment
                  (Server.MapPath(localFileName), "application/pdf"));

                  //Specify the smtp Server and port number to create a new instance of SmtpClient.
                  using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                      //passing the credentials for authentication
                      smtp.Credentials = new NetworkCredential
                      (ConfigurationSMTP.from, ConfigurationSMTP.password);
                      //Authentication required
                      smtp.EnableSsl = enableSSL;
                      //sending email.
          catch (Exception ex)
              //Error response
              Response.StatusCode = 400;
          return null;

2) Client Code

* Index.cshtml

This file contains two sections:

  • HTML and CSS code: used to create and design form controls
  • JavaScript code: used to capture the onsubmit event of contact form and build an HTTP request that invokes SendNewMessage method
<script type="text/javascript">

   $(document).ready(function () {
        $("#idFormContact").on("submit", function (e) {
            //call external service
            var url = "/Home/SendNewMessage";
            var formdata = (window.FormData) ? new FormData(this) : null;
            var fdata = (formdata !== null) ? formdata : $form.serialize();
            $("#idSubmitMvt").attr("disabled", true);

            //get authorization keys.
                type: "POST",
                url: url,
                data: fdata,
                processData: false,
                contentType: false,
                success: function (data) {
                error: function (xhr, ajaxOptions, thrownError) {


<div class="row">
    <h2>Contact Form</h2>
    <form class="col col-xs-6" id="idFormContact" >
        <div class="form-group">
            <input type="email" class="form-control" 
            name="to" value="" placeholder="Destination Email">
        <div class="form-group">
            <input type="text" class="form-control" 
            value="Test subject" 
            name="subject" placeholder="Subject">
        <div class="form-group">
            <textarea class="form-control"  
            name="message">Test Message</textarea>
        <button type="submit" 
        class="btn btn-primary">Submit</button>
        <div id="idNotifError" style="display:none" 
        class="alert alert-danger">Fail to send a message</div>
        <div id="idNotifSuccess" style="display:none" 
        class="alert alert-success">Message is sent</div>

C) Result

* enter data in the form, and submit.

Image 1

* the details of received message

Image 2

In Closing

I hope that you appreciated this post. Try to download the source code. Please send me your questions and comments.


  • v1 19/10/2016: Initial version


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

France France
Microsoft certified professional in C# ,HTML 5 & CSS3 and JavaScript,, and Microsoft Azure.

Comments and Discussions

QuestionHow to rebuild? Pin
Member 817711726-Oct-16 12:12
MemberMember 817711726-Oct-16 12:12 
AnswerRe: How to rebuild? Pin
O.Nasri26-Oct-16 22:58
professionalO.Nasri26-Oct-16 22:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 19 Oct 2016


10 bookmarked