I have a form that a customer is required to fill out. Once the form is submitted, I'd like to send the basic information from the form's Index view (First Name, Last Name, Phone Number, etc..) to an email. I'm currently using GoDaddy for my hosting site. Does this matter, or can I send the email directly from my MVC application? I have the following for my Model, View, Controller. I've never done this before and am really not sure how to go about it.
Model:
public class Application
{
public int Id { get; set; }
[DisplayName("Marital Status")]
public bool? MaritalStatus { get; set; }
[Required]
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("Middle Initial")]
public string MiddleInitial { get; set; }
[Required]
[DisplayName("Last Name")]
public string LastName { get; set; }
}
Controller:
public ActionResult Index()
{
return View();
}
// POST: Applications/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "Id,FirstName,MiddleInitial,LastName")] Application application)
{
ViewBag.SubmitDate = DateTime.Now;
if (ModelState.IsValid)
{
application.GetDate = DateTime.Now;
db.Applications.Add(application);
db.SaveChanges();
return RedirectToAction("Thanks");
}
return View(application);
}
View
<table class="table table-striped">
<tr>
<th>
@Html.ActionLink("First Name", "Index", new { sortOrder = ViewBag.NameSortParm })
</th>
<th>
@Html.ActionLink("Last Name", "Index", new { sortOrder = ViewBag.NameSortParm })
</th>
<th>
@Html.ActionLink("Date Submitted", "Index", new { sortOrder = ViewBag.NameSortParm})
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.GetDate)
</td>
</tr>
}
You will need an SMTP server to send email from. No idea how GoDaddy works but I'm sure they will provide something.
To send emails from an MVC app you either specify you SMTP details in code or in the web.config
. I recommend in the config file as it means it's much easier to change. With everything in the web.config:
SmtpClient client=new SmtpClient();
Otherwise, do it in code:
SmtpClient client=new SmtpClient("some.server.com");
//If you need to authenticate
client.Credentials=new NetworkCredential("username", "password");
Now you create your message:
MailMessage mailMessage = new MailMessage();
mailMessage.From = "someone@somewhere.com";
mailMessage.To.Add("someone.else@somewhere-else.com");
mailMessage.Subject = "Hello There";
mailMessage.Body = "Hello my friend!";
Finally send it:
client.Send(mailMessage);
An example for the web.config
set up:
<system.net>
<mailSettings>
<smtp>
<network host="your.smtp.server.com" port="25" />
</smtp>
</mailSettings>
</system.net>