MVC Contact Form with Email

mvc contact form example
asp net contact form
how to create contact us page in asp.net mvc
asp.net core contact form
asp.net contact form tutorial
c# contact form
asp net mvc send email using outlook
bootstrap contact form send email asp net

I wonder if someone can please help with a MVC Contact Form which send an Email on submission? I think I have most elements setup, but for some reason the form appear to be sending (takes ages) then just returns back to the form and no email is received.

MailModels.cs:

namespace WebApplication1.Models
{
    public class MailModels
    {
       public string Name { get; set; }
       public string Email { get; set; }
       public string Telephone { get; set; }
       public string Message { get; set; }
    }
}

Contact.cshtml:

@using (Html.BeginForm("Contact", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @id = "contact-form", role = "form" }))
{
    @Html.ValidationSummary()
    <fieldset>
        <div class="form-div-1">
            <label class="name">
                @Html.TextBoxFor(m => m.Name, new { @placeholder = "Name *", @type = "text" })
            </label>
        </div>
        <div class="form-div-2">
            <label class="email">
                @Html.TextBoxFor(m => m.Email, new { @placeholder = "Email Address *", @type = "email" })
            </label>
        </div>
        <div class="form-div-3">
            <label class="phone notRequired">
                @Html.TextBoxFor(m => m.Telephone, new { @placeholder = "Telephone Number", @type = "text" })
            </label>
        </div>
        <div>
            <label class="message">
                @Html.TextAreaFor(m => m.Message, new { @placeholder = "Message *" })
            </label>
        </div>
        <div class="button-wrapper">
            <input type="submit" value="Send" name="submit" class="button"> <input type="reset" value="Reset" name="MFReset" class="button"><span>* Required Fields</span>
        </div>
    </fieldset>
}

HomeController.cs:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using WebApplication1.Models;
using System.Text;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
    public ActionResult Contact()
    {
        ViewBag.Message = "Test Form";

        return View();
    }

    [HttpPost]
    public ActionResult Contact(MailModels e)
    {
        if (ModelState.IsValid)
        {

            StringBuilder message = new StringBuilder();
            MailAddress from = new MailAddress(e.Email.ToString());
            message.Append("Name: " + e.Name + "\n");
            message.Append("Email: " + e.Email + "\n");
            message.Append("Telephone: " + e.Telephone + "\n\n");
            message.Append(e.Message);

            MailMessage mail = new MailMessage();

            SmtpClient smtp = new SmtpClient();

            smtp.Host = "smtp.mail.yahoo.com";
            smtp.Port = 465;

            System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("yahooaccount", "yahoopassword");

            smtp.Credentials = credentials;
            smtp.EnableSsl = true;

            mail.From = from;
            mail.To.Add("yahooemailaddress");
            mail.Subject = "Test enquiry from "+e.Name;
            mail.Body = message.ToString();

            smtp.Send(mail);
        }
        return View();
    }

Banging my head against a brickwall with this one, any help would be much appreciated :-)


Sending an email will take time. It should be a thread. Put your code in a function. And make the following changes:

public void SendEmail(string toAddress, string fromAddress, 
                      string subject, string message)
{
    try
    {
        using (var mail = new MailMessage())
        {
            const string email = "username@yahoo.com";
            const string password = "password!";

            var loginInfo = new NetworkCredential(email, password);


            mail.From = new MailAddress(fromAddress);
            mail.To.Add(new MailAddress(toAddress));
            mail.Subject = subject;
            mail.Body = message;
            mail.IsBodyHtml = true;

            try
            {
                using (var smtpClient = new SmtpClient(
                                                 "smtp.mail.yahoo.com", 465))
                {
                    smtpClient.EnableSsl = true;
                    smtpClient.UseDefaultCredentials = false;
                    smtpClient.Credentials = loginInfo;
                    smtpClient.Send(mail);
                }

            }

            finally
            {
                //dispose the client
                mail.Dispose();
            }

        }
    }
    catch (SmtpFailedRecipientsException ex)
    {
        foreach (SmtpFailedRecipientException t in ex.InnerExceptions)
        {
            var status = t.StatusCode;
            if (status == SmtpStatusCode.MailboxBusy ||
                status == SmtpStatusCode.MailboxUnavailable)
            {
                Response.Write("Delivery failed - retrying in 5 seconds.");
                System.Threading.Thread.Sleep(5000);
                //resend
                //smtpClient.Send(message);
            }
            else
            {
                Response.Write("Failed to deliver message to {0}",
                                  t.FailedRecipient);
            }
        }
    }
    catch (SmtpException Se)
    {
        // handle exception here
        Response.Write(Se.ToString());
    }

    catch (Exception ex)
    {
        Response.Write(ex.ToString());
    }

}

Call that function in your controller:

[HttpPost]
public ActionResult Contact(MailModels e)
{
    if (ModelState.IsValid)
    {

        //prepare email
        var toAddress = "someadress@yahoo.co.uk";
        var fromAddress = e.Email.ToString();
        var subject = "Test enquiry from "+ e.Name;
        var message = new StringBuilder();
        message.Append("Name: " + e.Name + "\n");
        message.Append("Email: " + e.Email + "\n");
        message.Append("Telephone: " + e.Telephone + "\n\n");
        message.Append(e.Message);

        //start email Thread
        var tEmail = new Thread(() => 
       SendEmail(toAddress, fromAddress, subject, message));
        tEmail.Start();
    }
    return View();
}

If you dont get email, check your spam folder

asp.net-mvc - Contact Form In Asp MVC, asp.net-mvc documentation: Contact Form In Asp MVC. set; } [Required, Display(Name = "Sender Email"), EmailAddress] public string SenderEmail { get; set; }� This form generates an email receipt sent to a specified recipient. The information sent through this form may be saved by the recipient. Your information is protected under federal FERPA laws and is not shared with third-parties without your express consent.


settings to web.config

<system.net>
  <mailSettings>
    <smtp from="you@outlook.com">
      <network host="smtp-mail.outlook.com" 
               port="587" 
               userName="you@outlook.com"
               password="password" 
               enableSsl="true" />
    </smtp>
  </mailSettings>
</system.net>

Port 465 or 587?

Lots of code samples for Gmail feature port 465 but most people cannot get this to work. When they revert to port 587, their email suddenly works. According to Gmail's documentation SSL is required if you specify port 465. Many people think that setting EnableSsl to true achieves this, but in fact, it means that your app must be running under https. When you set EnableSsl to true, you actually switch TLS on, which is required for port 587. Https is not supported by the SmtpClient object. For more details, read the Remarks section of the docs on MSDN.

How to Implement Contact Us Page in ASP.NET MVC (ASP.NET 5 , At first, I have created Model for Contact form and view is created for that and This is Controller code where we are using Gmail to send mail. This form generates an email receipt sent to a specified recipient. The information sent through this form may be saved by the recipient. Your information is protected under federal FERPA laws and is not shared with third-parties without your express consent.


You need to implement Producer Consumer pattern for this use case. You will have to have one thread running dedicated to emails. This thread will read from the queue & send emails. In the contact method, you will just add to the queue. Its not a good idea to do time consuming operations in controller methods.

C# producer/consumer

Building a Contact Form Using C#/ASP.NET MVC, How it works: Build a message (using MailMessage() class) thanks to data received from HTTP request such as: 'Destination Email', 'Subject', 'Message Body'. Create and configure the SMTP client using SmtpClient() class. Attach a credentials parameter when trying the creation of SMTP connection (using smtp. This is a post about implementing Contact us Page in ASP.NET MVC 6 (ASP.NET core 1.0). At first, I have created Model for Contact form and view is created for that and then all the logical stuff is done in the Controller. This is implemented using MVC Pattern (Model View and Controller Pattern) and jQuery is used for Client side Validation


public void SendEmail(string toAddress, string fromAddress,string subject, string message)
{
    try
    {
        using (var mail = new MailMessage())
        {
            const string email = "username@yahoo.com";
            const string password = "password!";

            var loginInfo = new NetworkCredential(email, password);


            mail.From = new MailAddress(fromAddress);
            mail.To.Add(new MailAddress(toAddress));
            mail.Subject = subject;
            mail.Body = message;
            mail.IsBodyHtml = true;

            try
            {
                using (var smtpClient = new SmtpClient(
                                                 "smtp.mail.yahoo.com", 465))
                {
                    smtpClient.EnableSsl = true;
                    smtpClient.UseDefaultCredentials = false;
                    smtpClient.Credentials = loginInfo;
                    smtpClient.Send(mail);
                }

            }

            finally
            {
                //dispose the client
                mail.Dispose();
            }

        }
    }
    catch (SmtpFailedRecipientsException ex chor gai )
    {
        foreach (SmtpFailedRecipientException t in ex.InnerExceptions)
        {
            var status = t.StatusCode;
            if (status == SmtpStatusCode.MailboxBusye ||
                status == SmtpStatusCode.MailboxUnavailableee)
            {
                Response.Write("Delivery failed - retrying in 5 seconds.");
                System.Threading.Thread.Sleep(5000);
                //resend
                //smtpClient.Send(message);
            }
            else
            {
                Response.Write("Failed to deliver message to {0}",
                                  t.FailedRecipient);
            }
        }
    }
    catch (SmtpException Se)
    {
        // handle exception here
        Response.Write(Se.ToString());
    }

    catch (Exception ex)
    {
        Response.Write(ex.Toread());
    }
}

How To Make a Basic Working Contact Form With ASP .NET Core , NET Core MVC and MailKit. 2018-08-04. Modern day website owners prefer not to leave their email address open and exploitable on the internet. Enter the� Basic Email Sending The most common use for email in a web setting is to enable visitors to provide feedback or make contact with the site owners via a form. The following steps will walk you through creating a new MVC 5 application, adding a view model and view, and then creating an action method to process a form submission to generate an email.


Send EMail From Contact Form in ASP.NET Core MVC, In this video, I will demo how to Send EMail From Contact Form in ASP.NET Core MVC To Duration: 32:34 Posted: Dec 3, 2018 Telephone the 24-hour MVC Tip Line toll-free at 866-TIPS-MVC (1-866-847-7682) to report suspected fraud or criminal behavior that is related to MVC operations. The tipster will receive an automated instruction to briefly recite the details of the fraud tip on the recorded line. These tips will be reviewed after hours by a fraud investigator.


ASP.NET MVC #20 : Create Contact Form Flat Responsive , create contact form asp net how to make a contact form in mvc bootstrap contact form mvc Duration: 11:29 Posted: Apr 4, 2017 New Jersey Motor Vehicle Commission. P.O. Box 160 Trenton, NJ 08666 (609) 292-6500 If you are deaf or hard of hearing, please use 7-1-1 NJ Relay


How to setup a contact us form?, I've not touched MVC for years and I'm slowly coming back to asp.net. by step instruction on how to create/setup the contact us form in MVC? within your form so that you know // who to send the email to string address� Through this tip, you will learn in a step by step manner to easily send email using System.Net.Mail. Background This tip may be useful for intermediate developers who have some basics in C#, ASP.NET MVC, JQuery, JavaScript.