下面是一个使用Gmail的SMTP例子,但如果你有自己的SMTP服务器,你可以很容易地调整代码。
一如既往我将与视图模型开始:
public class QuestionViewModel
{
[Required]
public string Question { get; set; }
public HttpPostedFileBase Attachment { get; set; }
}
然后控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new QuestionViewModel());
}
[HttpPost]
public ActionResult Index(QuestionViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
using (var client = new SmtpClient("smtp.gmail.com", 587))
{
client.EnableSsl = true;
client.Credentials = new NetworkCredential("[email protected]", "secret");
var mail = new MailMessage();
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Test mail";
mail.Body = model.Question;
if (model.Attachment != null && model.Attachment.ContentLength > 0)
{
var attachment = new Attachment(model.Attachment.InputStream, model.Attachment.FileName);
mail.Attachments.Add(attachment);
}
client.Send(mail);
}
return Content("email sent", "text/plain");
}
}
和最后一个视图:
@model QuestionViewModel
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
<div>
@Html.LabelFor(x => x.Question)
@Html.TextAreaFor(x => x.Question)
</div>
<div>
<label for="attachment">Attachment</label>
<input type="file" name="attachment" id="attachment"/>
</div>
<input type="submit" value="Send" />
</fieldset>
}
进一步改进这个代码将实际发送的邮件外部化到实现某个接口并使用D的存储库中我为了削弱控制器逻辑和邮件发送逻辑之间的耦合。
请注意,您也可以在web.config中配置SMTP设置:
<system.net>
<mailSettings>
<smtp from="[email protected]" deliveryMethod="Network">
<network
enableSsl="true"
host="smtp.gmail.com"
port="587"
userName="[email protected]"
password="secret"
/>
</smtp>
</mailSettings>
</system.net>
,然后简单地说:
using (var client = new SmtpClient())
{
var mail = new MailMessage();
mail.To.Add("[email protected]");
mail.Subject = "Test mail";
mail.Body = model.Question;
if (model.Attachment != null && model.Attachment.ContentLength > 0)
{
var attachment = new Attachment(model.Attachment.InputStream, model.Attachment.FileName);
mail.Attachments.Add(attachment);
}
client.Send(mail);
}
Tkanks很多!它工作的很棒:) – Marta 2011-06-08 17:39:21
toaddress?我不知道蟾蜍穿着连衣裙! – AaronLS 2011-08-31 15:00:14
如果您试图使用$ .ajax来传递您的'HttpPostedFileBase'文件,该怎么办?我试图通过一个简单的$ .ajax调用来完成,但我的控制器上有一个空文件。它是我缺少的内容类型吗? – AdrianoRR 2011-10-05 17:26:31