I've implemented a code that should allow me to send email to gmail from my web application and I can't figure out what is wrong with it...
When I press the "Submit" button nothing happens, there are no errors. I also added breakpoints in my controller but they are not fired...
Here is my code:
Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.ComponentModel.DataAnnotations;
namespace TripPlanner.Models
{
public class EmailFormModel
{
[Required]
[StringLength(20, MinimumLength = 5)]
public string Name { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
public string Subject { get; set; }
[Required]
public string Message { get; set; }
}
}
View:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TripPlanner.Models.EmailFormModel>" %>
<% using (Html.BeginForm()) {%>
<form method="post">
<%: Html.ValidationSummary("Please correct the errors and try again.") %>
<p>Name: </p>
<%: Html.TextBoxFor(m => m.Name)%>
<p>Email: </p>
<%: Html.TextBoxFor(m => m.Email)%>
<p>Subject: </p>
<%: Html.TextBoxFor(m => m.Subject)%>
<p>Message: </p>
<%: Html.TextBoxFor(m => m.Message)%>
<input type ="submit" value ="Send" />
</form>
<% } %>
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Web.Mvc;
using System.IO;
using System.Net;
using TripPlanner.Models;
namespace TripPlanner.Controllers
{
public class SendMailerController: Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(EmailFormModel vm)
{
if(ModelState.IsValid)
{
try
{
MailMessage msz = new MailMessage();
msz.From = new MailAddress(vm.Email);//Email which you are getting from contact us page
msz.To.Add("my_valid_email@gmail.com");//Where mail will be sent
msz.Subject = vm.Subject;
msz.Body = vm.Message;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("my_valid_email@gmail.com", "my_valid_pass");
smtp.EnableSsl = true;
smtp.Send(msz);
ModelState.Clear();
}
catch(Exception ex )
{
ModelState.Clear();
}
}
return View();
}
public ActionResult Error()
{
return View();
}
}
}