Приложение электронной почты ASP.Net MVC 5 не присоединяется - PullRequest
0 голосов
/ 31 января 2019

Я не получаю никаких ошибок, а само сообщение получено.Вложение не входит.

Я не часто программирую на сайте.Компания попросила меня добавить это, и это далеко, как я пришел через другие руководства.Любая информация приветствуется!

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 голосов
/ 31 января 2019

Вы должны установить enctype в качестве свойства формы для загрузки файла.

Пожалуйста, используйте следующее

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

        }

Пожалуйста, смотрите подобное обсуждение в этом SO thread.

...