表格附件上传和电子邮件发送

Mar*_*rta 17 c# forms razor asp.net-mvc-3

我需要使用textarea和图片上传字段制作表单.当有人提交它时,我希望它发送电子邮件(带有来自textarea的文本)和附件(从输入文件上传字段)给我.

我的简单形式看起来像这样:

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>        
            @Html.TextArea("Question");      
            <input type="file"/> 
            <input type="submit" value="Send" />

    </fieldset>

}
Run Code Online (Sandbox Code Playgroud)

我发现PHP脚本正在做类似的事情,但我怎么能在ASP.NET MVC中做到这一点(可能是用JavaScript)?

Dar*_*rov 28

以下是使用gmail的SMTP的示例,但如果您有自己的SMTP服务器,则可以轻松调整代码.

像往常一样,我将从视图模型开始:

public class QuestionViewModel
{
    [Required]
    public string Question { get; set; }

    public HttpPostedFileBase Attachment { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后一个控制器:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

最后一个观点:

@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>
}
Run Code Online (Sandbox Code Playgroud)

对该代码的进一步改进是将邮件的实际发送外部化到实现某个接口并使用DI的存储库中,以便削弱控制器逻辑和邮件发送逻辑之间的耦合.

请注意,您还可以在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>
Run Code Online (Sandbox Code Playgroud)

然后简单地说:

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);
}
Run Code Online (Sandbox Code Playgroud)