如何将用户输入的邮件正文及附件传递至ASP.NET MVC控制器?
该操作完全可行
下面是具体的实现思路和代码示例:
1. 前端表单配置
要确保表单的enctype设置为multipart/form-data,这样才能正确传递文件和文本内容:
<form action="@Url.Action("SendEmail", "Home")" method="post" enctype="multipart/form-data"> <div> <label>评论内容:</label> <textarea name="comment" rows="5" cols="50" required></textarea> </div> <div> <label>上传附件:</label> <input type="file" name="attachments" multiple accept=".pdf,.doc,.docx,.txt" /> </div> <button type="submit">发送邮件</button> </form>
multiple属性允许用户上传多个附件,accept可限制允许上传的文件类型name属性要和控制器参数名一一对应
2. MVC控制器接收数据
在控制器中通过HttpPost方法接收文本内容和附件,并处理邮件发送逻辑:
using System.Net.Mail; using System.Web; using System.Web.Mvc; public class HomeController : Controller { [HttpPost] public ActionResult SendEmail(string comment, IEnumerable<HttpPostedFileBase> attachments) { // 基础输入验证 if (string.IsNullOrEmpty(comment) && (attachments == null || !attachments.Any())) { ModelState.AddModelError("", "请输入评论或上传附件"); return View(); } bool emailSent = SendOutlookEmail(comment, attachments); ViewBag.Message = emailSent ? "邮件发送成功" : "邮件发送失败"; return View(); } private bool SendOutlookEmail(string comment, IEnumerable<HttpPostedFileBase> attachments) { try { using (var mail = new MailMessage()) { // 配置邮件基本信息 mail.From = new MailAddress("your-email@outlook.com"); mail.To.Add("recipient@example.com"); mail.Subject = "用户评论及附件"; mail.Body = comment; mail.IsBodyHtml = false; // 若需HTML格式内容可改为true // 添加附件 if (attachments != null) { foreach (var file in attachments) { if (file != null && file.ContentLength > 0) { mail.Attachments.Add(new Attachment(file.InputStream, file.FileName)); } } } // 配置Outlook SMTP服务器 using (var smtp = new SmtpClient("smtp.office365.com", 587)) { smtp.Credentials = new System.Net.NetworkCredential("your-email@outlook.com", "your-password"); smtp.EnableSsl = true; smtp.Send(mail); } return true; } } catch (Exception) { // 可在此添加错误日志记录逻辑 return false; } } }
关键注意事项
- 若使用新版.NET(非.NET Framework),建议用
MailKit库替代已过时的SmtpClient - Outlook的SMTP配置需保持最新(当前主流为端口587、启用SSL)
- 生产环境中禁止硬编码邮箱密码,应通过配置文件或密钥管理器存储
- 如需支持大文件上传,需在Web.config中调整
maxRequestLength和requestLengthDiskThreshold参数
内容的提问来源于stack exchange,提问作者Bala Vignesh
相关产品推荐
相关产品推荐

