-
StackOverflow 文件
-
asp.net-mvc 教程
-
Asp.net mvc 傳送郵件
-
聯絡表格在 Asp MVC 中
1.型號:
public class ContactModel
{
[Required, Display(Name="Sender Name")]
public string SenderName { get; set; }
[Required, Display(Name = "Sender Email"), EmailAddress]
public string SenderEmail { get; set; }
[Required]
public string Message { get; set; }
}
2.控制器:
public class HomeController
{
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Contact(ContectModel model)
{
if (ModelState.IsValid)
{
var mail = new MailMessage();
mail.To.Add(new MailAddress(model.SenderEmail));
mail.Subject = "Your Email Subject";
mail.Body = string.Format("<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>", model.SenderName, mail.SenderEmail, model.Message);
mail.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(mail);
return RedirectToAction("SuccessMessage");
}
}
return View(model);
}
public ActionResult SuccessMessage()
{
return View();
}
}
3. Web.Config:
<system.net>
<mailSettings>
<smtp from="you@outlook.com">
<network host="smtp-mail.outlook.com"
port="587"
userName="you@outlook.com"
password="password"
enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
4.檢視:
@model ContectModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<h4>Send your comments.</h4>
<hr />
<div class="form-group">
@Html.LabelFor(m => m.SenderName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.SenderName, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.SenderName)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.SenderEmail, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.SenderEmail, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.SenderEmail)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Message, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextAreaFor(m => m.Message, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Message)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Send" />
</div>
</div>
}
SuccessMessage.cshtml
<h2>Your message has been sent</h2>