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

本文关键字:电子邮件 表格 | 更新日期: 2023-09-27 17:58:46

我需要制作带有文本区域和图像上传字段的表单。当有人提交它时,我希望它向我发送电子邮件(来自文本区域的文本)并附上附件

我的简单表单是这样的:

@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服务器,你可以很容易地调整代码。

和往常一样,我会从一个视图模型开始:

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("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");
    }
}

最后是一个视图:

@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>
}

对该代码的进一步改进是将邮件的实际发送外部化到实现某种接口并使用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>

然后简单地说:

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);
}

.NET中的MailMessage类应该能够为您处理这个问题:

http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.attachments.aspx

或者您正在寻找更具体的代码?(例如,如何读取文件并将其添加到附件中)?

  if (model.Attachment != null && model.Attachment.ContentLength > 0)
    {
    foreach (HttpPostedFileBase item in fileUploader)
      {
        var attachment = new Attachment(model.Attachment.InputStream,   model.Attachment.FileName);
        mail.Attachments.Add(attachment);
      }
    }

除了Daren的答案之外,您不必在视图中对文件上传的输入和标签进行硬编码。把这个放在那里:)

@Html.TextBoxFor(model => model.Attachment, new { type = "file" })
@Html.LabelFor(model => model.Attachment)