0

I don't receive any errors, and the message itself is received. The attachment isn't included.

I do not program for the website often. The company asked me to add this and this is far as I've come via other guides. Any information is appreciated!

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>
            }

The method:

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

}

The controller:

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

}

Sangam Belose
  • 4,262
  • 8
  • 26
  • 48
  • I would try testing without google Captcha and Body with HTML=true if its working then something to do with Captha it happens to me ones – charithsuminda Jan 31 '19 at 04:56
  • This has some answers that might help: https://stackoverflow.com/questions/21677038/mvc-upload-file-with-model-second-parameter-posted-file-is-null – Ben Jan 31 '19 at 04:58
  • Your this piece of code looks fishy `if (c.FileUploader != null) { string fileName = Path.GetFileName(c.FileUploader.FileName); msg.Attachments.Add(new Attachment(c.FileUploader.InputStream, fileName)); }`. Do you have a physical file to be added as an attachment or you have read the file in memory stream and then using the stream to add an attachment – mdowes Jan 31 '19 at 05:01
  • The 2nd argument to Attachment constructor is the Content-Type property and you are passing filename to it. You should use a string content-type like MediaTypeNames.Application.Octet, MediaTypeNames.Application.Pdf, text/csv depending on the file type. – mdowes Jan 31 '19 at 05:09

1 Answers1

0

You have to set the enctype to the form property for the file uploads.

Please use the following

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

        }

Please see the similar discussion in this SO thread.

Rasik Jain
  • 1,026
  • 6
  • 14
  • The question is not about "Error while uploading a file". The file is already within the application, the problem occurs when sending the file as an attachment via email – mdowes Jan 31 '19 at 05:03
  • This worked! Thank you! I knew it was something very simply that I was overlooking. Thanks for the extra set of eyes!! – g1ng3r_girl Jan 31 '19 at 15:53
  • Hi @g1ng3r-girl, Glad it worked for you. if this or any answer has solved your question please consider [accepting it](https://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – Rasik Jain Feb 02 '19 at 12:31