【问题标题】:Email Attachment ASP.Net MVC 5 not attaching电子邮件附件 ASP.Net MVC 5 未附加
【发布时间】:2019-01-31 04:47:30
【问题描述】:

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

我不经常为网站编程。公司要求我添加这个,这是我通过其他指南获得的。任何信息表示赞赏!

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

}

【问题讨论】:

  • 我会尝试在没有 google Captcha 和 Body 的情况下使用 HTML=true 进行测试,如果它可以正常工作,那么与 Captha 相关的事情发生在我身上
  • 这有一些可能有帮助的答案:stackoverflow.com/questions/21677038/…
  • 你的这段代码看起来很可疑if (c.FileUploader != null) { string fileName = Path.GetFileName(c.FileUploader.FileName); msg.Attachments.Add(new Attachment(c.FileUploader.InputStream, fileName)); }。您是否有要作为附件添加的物理文件,或者您已在内存流中读取文件,然后使用流添加附件
  • Attachment 构造函数的第二个参数是 Content-Type 属性,您将文件名传递给它。您应该使用字符串内容类型,例如 MediaTypeNames.Application.Octet、MediaTypeNames.Application.Pdf、text/csv,具体取决于文件类型。

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


【解决方案1】:

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

请使用下面的

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

        }

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

【讨论】:

  • 问题不在于“上传文件时出错”。该文件已经在应用程序中,通过电子邮件将文件作为附件发送时会出现问题
  • 这成功了!谢谢!我知道这是我忽略的非常简单的事情。谢谢你多一双眼睛!!
  • 嗨@g1ng3r-girl,很高兴它对你有用。如果此答案或任何答案解决了您的问题,请单击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
猜你喜欢
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
  • 2015-11-07
  • 2015-05-29
  • 2011-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多