【发布时间】:2016-08-30 23:59:54
【问题描述】:
我已经实现了一个代码,应该允许我从我的网络应用程序向 gmail 发送电子邮件,但我不知道它有什么问题......
当我按下“提交”按钮时,没有任何反应,也没有错误。我还在控制器中添加了断点,但它们没有被触发......
这是我的代码:
型号:
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; }
}
}
查看:
<%@ 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>
<% } %>
控制器:
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();
}
}
}
【问题讨论】:
-
你确定没有抛出异常吗?你似乎在你的 catch 块中吞下了异常。
标签: c# asp.net asp.net-mvc-3 smtp