In my code below I am trying to create a contact form that has the fields first name, last name, email, comment. When the submit button is pressed I need it to send an email to my Gmail address. I've looked at many guides, forums, tips from all over. Most of my code is based on http://ryanbutler.org/content/aspmvcform/documents/aspmvccontactform.pdf and has been modified in areas I thought would help to get this functioning based on other articles I've read.
My environment:
IDE: Visual Studio 2013 Express for Web
Using IIS 8 Express
Deployment will go to Azure
My Os: Windows 8.1
Error Message after clicking submit and filling out the form:
Error. An error occurred while processing your request.
My questions are: Is there anything wrong with my code? Or could the problem lie not with the code but the server IIS Express or another area? I ask this because I've read somewhere that IIS Express does not support SMTP.
The Controller is:
using MySite.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
namespace MySite.Controllers
{
public class SendMailerController : Controller
{
//
// GET: /SendMailer/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Contact(ContactModels c)
{
if (ModelState.IsValid)
{
try
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
msg.To.Add("[email protected]");
msg.Subject = "Contact Us";
msg.Body = "First Name: " + c.FirstName;
msg.Body += "Last Name: " + c.LastName;
msg.Body += "Email: " + c.Email;
msg.Body += "Comments: " + c.Comment;
msg.IsBodyHtml = false;
smtp.Host = "smtp.gmail.com";
smtp.Port = 25;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false; //
smtp.Credentials = new NetworkCredential("[email protected]", "MyGmailPassword");
smtp.Host = "smtp.gmail.com";
smtp.Send(msg);
msg.Dispose();
return View("Success");
}
catch (Exception)
{
return View("Error");
}
}
return View();
}
}
}
My questions are: Is there anything wrong with my code?
Yes, smtp.gmail.com
requires secure connection and is not available on port 25. Try this:
using (var client = new SmtpClient("smtp.gmail.com", 587))
{
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("MyGmailAddress", "Your Gmail Password");
string body = string.Format(
"First Name: {0}, Last Name: {1}, Email: {2}, Comment: {3}",
c.FirstName,
c.LastName,
c.Email,
c.Comment
);
var message = new MailMessage(
"[email protected]",
"[email protected]",
"Contact Us",
"mail body"
);
message.IsBodyHtml = false;
client.Send(message);
}