我的mvc网站上有反馈表,看起来像是
我需要将表单发送到电子邮箱。
我为我的表单创建了模型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ComponentTrading.Web.Models
{
public class FeedbackForm
{
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Message { get; set; }
}
}
我为我的表单Contacts.cshtml
创建了视图 @using (Html.BeginForm("Contacts", "Home", FormMethod.Post, new { id = "contact-form" }))
{
<fieldset>
@Html.TextBoxFor(model => model.Name, new { @Value = Name })
@Html.TextBoxFor(model => model.Email, new { @Value = "E-mail" })
@Html.TextBoxFor(model => model.Phone, new { @Value = Phone })
@Html.TextAreaFor(model => model.Message, new { @class = "img-shadow" })
<input class="form-button" data-type="reset" value="Clear" />
<input class="form-button" data-type="submit" type="submit" value="Send" />
</fieldset>
}
我在我的控制器上写了这段代码
[HttpGet]
public ActionResult Contacts()
{
FeedbackForm temp = new FeedbackForm();
temp.Message = @Resources.Global.Contacts_Form_Message_Field;
return View(temp);
}
[HttpPost]
public ActionResult Contacts(FeedbackForm Model)
{
string Text = "<html> <head> </head>" +
" <body style= \" font-size:12px; font-family: Arial\">"+
Model.Message+
"</body></html>";
SendEmail("tayna-anita@mail.ru", Text);
FeedbackForm tempForm = new FeedbackForm();
return View(tempForm);
}
public static bool SendEmail(string SentTo, string Text)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("Test@mail.ru");
msg.To.Add(SentTo);
msg.Subject = "Password";
msg.Body = Text;
msg.Priority = MailPriority.High;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.mail.ru", 25);
client.UseDefaultCredentials = false;
client.EnableSsl = false;
client.Credentials = new NetworkCredential("TestLogin", "TestPassword");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
//client.EnableSsl = true;
try
{
client.Send(msg);
}
catch (Exception)
{
return false;
}
return true;
}
我的代码没有任何错误, 但是当我按下发送按钮时,我没有收到电子邮件,我的表格也没有变得清晰。
我使用了Fiddler Web Debugger,我得到了Send-button click
我认为,这意味着可以,所以我不能忽视什么是错的?
答案 0 :(得分:2)
我已经复制粘贴了您的代码并通过一些小的修改使其工作:
Credentials
属性我修改了模板以删除@Value属性:
@ Html.TextBoxFor(model =&gt; model.Name) @ Html.TextBoxFor(model =&gt; model.Email) @ Html.TextBoxFor(model =&gt; model.Phone)
这些是我所做的唯一更改,我让您的应用程序正常运行。这让我相信SMTP客户端的配置一定有问题。你能检查一下client.Send(msg);
抛出的异常吗?我希望它会说一些关于无效网络凭证的事情。
答案 1 :(得分:1)
更改
catch (Exception)
{
return false;
}
到
catch (Exception ex)
{
// breakpoint here, inspect ex
return false;
}