电子邮件附件ASP.Net MVC 5不重视

时间:2019-01-31 04:47:30

标签: asp.net asp.net-mvc forms asp.net-mvc-5 email-attachments

我没有收到任何错误,并且消息本身也已收到。不包括附件。

我不经常为该网站编程。该公司要求我添加此内容,这与我从其他指南中获得的信息相去甚远。任何信息被理解!

Index.cshtml:

@using (Html.BeginForm())
            {
                //Captcha authentication
                @Html.AntiForgeryToken()
                //Form entry field validation
                @Html.ValidationSummary(true)
                <div class="row">
                    <div class="form-group col-lg-4">
                        @Html.LabelFor(model => model.Name, "Name")<br />
                        @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Name)
                    </div>
                    <div class="form-group col-lg-4">
                        @Html.LabelFor(model => model.Email, "Email Address")<br />
                        @Html.EditorFor(model => model.Email)
                        @Html.ValidationMessageFor(model => model.Email)
                    </div>
                    <div class="form-group col-lg-4">
                        @Html.LabelFor(model => model.Telephone, "Phone Number")<br />
                        @Html.EditorFor(model => model.Telephone)
                        @Html.ValidationMessageFor(model => model.Telephone)
                    </div>
                    <div class="clearfix"></div>
                    <div class="form-group col-lg-12">
                        @Html.LabelFor(model => model.Comment, "Message")<br />
                        @Html.TextAreaFor(model => model.Comment, new { @class = "text-boxMessage" })
                        @Html.ValidationMessageFor(model => model.Comment)
                    </div>
                    <div class="form-group col-lg-4">                             
                        <input type="file" name="fileUploader"/>
                    </div>
                </div>
                <div class="row">
                    <div class="g-recaptcha" data-sitekey="6Lcvzo0UAAAAAAdAu2zUmDIODBEDTsDvzmgANNdb"></div>
                    <div class="form-group col-lg-12">
                        <input class="btn btn-default" type="submit" value="Submit" />
                    </div>
                </div>
            }

方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace Mvc4ContactForm.Models
{
    public class ContactModels
    {
        [Required(ErrorMessage="*Required")]
        public string Name { get; set; }
        [Required(ErrorMessage= "*Required")]
        [RegularExpression(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$", ErrorMessage = "Invalid email")]
        public string Email { get; set; }
        [Required(ErrorMessage = "*Required")]
        public string Telephone { get; set; }
        [Required(ErrorMessage= "*Required")]
        public string Comment { get; set; }

    public HttpPostedFileBase FileUploader { get; set; }
}

}

控制器:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using Mvc4ContactForm.Models;

namespace correinc.Controllers
{
  public class ContactController : Controller
  {
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    //For captcha
    [ValidateAntiForgeryToken]
    public ActionResult Index(ContactModels c)
    {
        if (ModelState.IsValid)
        {
            //For captcha
            CaptchaResponse response = ValidateCaptcha(Request["g-recaptcha-response"]);
            if (response.Success && ModelState.IsValid)
            {
                //For data to smtp
                try
                {
                    MailMessage msg = new MailMessage();
                    SmtpClient client = new SmtpClient();
                    MailAddress from = new MailAddress(c.Email.ToString());
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();

                    msg.IsBodyHtml = false;
                    client.Host = "smtp.gmail.com";
                    client.Port = 587;
                    client.EnableSsl = true;
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    client.Credentials = new System.Net.NetworkCredential("a@b.com", "password");
                    msg.To.Add("b@b.com");
                    msg.From = from;
                    msg.Subject = "Website Contact Form";
                    sb.Append("Name: " + c.Name);
                    sb.Append(Environment.NewLine);
                    sb.Append("Email: " + c.Email);
                    sb.Append(Environment.NewLine);
                    sb.Append("Telephone: " + c.Telephone);
                    sb.Append(Environment.NewLine);
                    sb.Append("Comments: " + c.Comment);
                    //Fileuploader
                    if (c.FileUploader != null)

                    {
                        string fileName = Path.GetFileName(c.FileUploader.FileName);
                        msg.Attachments.Add(new Attachment(c.FileUploader.InputStream, fileName));
                    }
                    msg.IsBodyHtml = false;
                    msg.Body = sb.ToString();
                    client.Send(msg);
                    msg.Dispose();
                    return View("Success");
                }
                catch (Exception)
                {
                    return View("Error");
                }
            }
            //Captcha
            else
            {
                return Content("Error From Google ReCaptcha : " + response.ErrorMessage[0].ToString());
            }                    
        }
        return View();
    }

    //Captcha
    public class CaptchaResponse
    {
        [JsonProperty("success")]
        public bool Success
        {
            get;
            set;
        }
        [JsonProperty("error-codes")]
        public List<string> ErrorMessage
        {
            get;
            set;
        }
    }
    public static CaptchaResponse ValidateCaptcha(string response)
    {
        string secret = System.Web.Configuration.WebConfigurationManager.AppSettings["recaptchaPrivateKey"];
        var client = new System.Net.WebClient();
        var jsonResult = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, response));
        return JsonConvert.DeserializeObject<CaptchaResponse>(jsonResult.ToString());
    }
}

}

1 个答案:

答案 0 :(得分:0)

您必须将 enctype 设置为表单属性,以便上传文件。

请使用以下

  @using (Html.BeginForm("Index", "Contact", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
          ....
          ....

        }

请参见此SO线程中的类似讨论。