下面是一個使用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