所以我一直在尝试在我正在制作的网站上附加/上传多个文件。姓名,电子邮件,主题和&消息正在发送,但消息中没有附件。文件进入“〜/ App_Data / uploads”文件夹,它在那里,但我没有通过电子邮件收到它。我无法弄清楚出了什么问题。请帮我。我是这种东西的新手。谢谢!这是视图代码:
@using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="col-md-4">
<div class="contact_form block">
<div class="row">
<div class="col-md-12 col-sm-12">
<div id="note"></div>
</div>
</div>
<div id="fields">
<div class="col-md-12 col-sm-6">
@Html.LabelFor(m => m.FromName)
@Html.TextBoxFor(m => m.FromName, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.FromName)
</div>
<div class="col-md-12 col-sm-6">
@Html.LabelFor(m => m.FromEmail)
@Html.TextBoxFor(m => m.FromEmail, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.FromEmail)
</div>
<div class="clear"></div>
<div class="col-md-12 col-sm-6">
@Html.LabelFor(m => m.FromSubject)
@Html.TextBoxFor(m => m.FromSubject, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.FromSubject)
</div>
<div class="col-md-12 col-sm-6">
<form action="" method="post" enctype="multipart/form-data">
<label for="file1">Attachments</label>
<input type="file" name="files" id="file1" multiple/>
</form>
</div>
<div class="col-md-12">
@Html.LabelFor(m => m.Message)
@Html.TextAreaFor(m => m.Message, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Message)
</div>
<div class="col-md-12">
<div>
@if ((TempData["recaptcha"]) != null)
{
<p>@TempData["recaptcha"]</p>
}
</div>
<div class="g-recaptcha" data-sitekey="6LfVHx8TAAAAAMTDxxQrHDCxO1SyXf1GgbgNBZ5a"></div>
</div>
<div class="col-md-12"><input class="shortcode_button" type="submit" value="Send"></div>
</div>
</div>
</div>
}
这是控制器:
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(EmailFormModel model, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
//logic here upload file logic here.
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
}
//Rest of business logic here
string EncodedResponse = Request.Form["g-Recaptcha-Response"];
bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false);
if (IsCaptchaValid)
{
var body = "<p>Email From: {0} ({1})</p><p>Subject: {2} </p><p>Message:</p><p>{3}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress("***@gmail.com")); // replace with valid value
message.From = new MailAddress("***@ymailcom"); // replace with valid value
message.Subject = "Your email subject";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.FromSubject, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "***@gmail.com", // replace with valid value
Password = "***" // replace with valid value
};
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
//return RedirectToAction("Sent");
ViewBag.Message = "Your message has been sent!";
//TempData["message"] = "Message sent";
ModelState.Clear();
return View("Index");
}
}
else
{
TempData["recaptcha"] = "Please verify that you are not a robot!";
}
}
return View(model);
}
答案 0 :(得分:1)
您没有在代码中附加任何内容。您需要将文件附加到MailMessage
。
保存文件时,请跟踪列表中的路径。
List<string> paths = new List<string>();
//...other code
foreach (var file in files) {
//...other code removed for brevity
//keep file path for attachments
paths.Add(path);
}
创建消息时,您可以附加文件
//Attach files
foreach (var path in paths) {
//For file information
var fileInfo = new FileInfo(path);
//stream to store attachment
var memoryStream = new MemoryStream();
//copy file from disk to memory
using (var stream = fileInfo.OpenRead()) {
stream.CopyTo(memoryStream);
}
//reset memory pointer
memoryStream.Position = 0;
//get file name for attachment based on path
string fileName = fileInfo.Name;
//add attachment to message
message.Attachments.Add(new Attachment(memoryStream, fileName));
}
根据文件保存到磁盘的路径附加文件。可以重构此代码以获得更好的内存管理和性能,但这只是一个开始。你应该能够处理其余的事情。
答案 1 :(得分:0)
替换这部分代码并检查它是否有效
if (fileUploader != null)
{
HttpPostedFileBase fileUploader;
string fileName = Path.GetFileName(fileUploader.FileName);
mail.Attachments.Add(new Attachment(fileUploader.InputStream, fileName));
}