Reputation: 1344
Basically I have an MVC 3 form which sends a mail to my inbox when someone leaves a message on my site.
For some reason it throws an SmtpException with the message: "Failure sending mail."
[HttpPost]
public ActionResult Contact(string name, string email, string message)
{
string From = "contactform@******.com";
string To = "info@******.com";
string Subject = name;
string Body = name + " wrote:<br/><br/>" + message;
System.Net.Mail.MailMessage Email = new System.Net.Mail.MailMessage(From, To, Subject, Body);
System.Net.Mail.SmtpClient SMPTobj = new System.Net.Mail.SmtpClient("smtp.**********.net");
SMPTobj.EnableSsl = false;
SMPTobj.Credentials = new System.Net.NetworkCredential("info@*******.com", "*******");
try
{
SMPTobj.Send(Email);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
throw new Exception();
}
return View();
}
Could this be something to do with testing it locally rather than testing it on a server?
Upvotes: 1
Views: 1043
Reputation: 140
I would recommend you to try not to rethrow a new exception but just use
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
throw;
}
rethrowing an exception resets the stack, so you can't reliably trace the source of the error. In this case (without rethrowing) you can probably see the InnerException and Status properties in visual studio usually this will give you more details on the reason of the failure. (Often isp's block port 25 smtp traffic, in case you are testing locally)
Second you can try to configure all the connection details in web.config rather then hard coded in your application that makes it easier to test changes. See below for an example using gmail:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="[email protected]">
<network host="smtp.gmail.com" userName="[email protected]" password="password" enableSsl="true" port="587" />
</smtp>
</mailSettings>
Upvotes: 1