我需要制作带有文本区域和图片上传字段的表单。当有人提交它时,我希望它发送电子邮件(带有来自文本区域的文本)带有附件(来自输入文件上传字段)给我。
我的简单表单如下所示:
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
@Html.TextArea("Question");
<input type="file"/>
<input type="submit" value="Send" />
</fieldset>
}
我发现 PHP 脚本正在执行类似的操作,但我如何在 ASP.NET MVC 中执行此操作(可以使用 JavaScript)?
最佳答案
这是一个使用 gmail 的 SMTP 的示例,但如果您有自己的 SMTP 服务器,您可以轻松地调整代码。
一如既往,我会从一个 View 模型开始:
public class QuestionViewModel
{
[Required]
public string Question { get; set; }
public HttpPostedFileBase Attachment { get; set; }
}
然后是一个 Controller :
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("someaccount@gmail.com", "secret");
var mail = new MailMessage();
mail.From = new MailAddress("fromaddress@gmail.com");
mail.To.Add("toaddress@gmail.com");
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");
}
}
最后是一个 View :
@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>
}
对该代码的进一步改进是将邮件的实际发送外部化到存储库中,实现一些接口(interface)并使用 DI 以削弱 Controller 逻辑和邮件发送逻辑之间的耦合。
请注意,您还可以在 web.config 中配置 SMTP 设置:
<system.net>
<mailSettings>
<smtp from="fromaddress@gmail.com" deliveryMethod="Network">
<network
enableSsl="true"
host="smtp.gmail.com"
port="587"
userName="someaccount@gmail.com"
password="secret"
/>
</smtp>
</mailSettings>
</system.net>
然后简单地:
using (var client = new SmtpClient())
{
var mail = new MailMessage();
mail.To.Add("toaddress@gmail.com");
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);
}
关于c# - 带有附件上传和电子邮件发送的表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6282049/