Heidel
Heidel

Reputation: 3254

Attachment is not attached to the email asp.net mvc

I have two forms on my mvc site, FeedbackForm and CareerForm. I need to send both forms to the same email. I created two models for my forms and two views, then I added in the first my controller

    /*Feedback*/
    [HttpGet]
    public ActionResult Feedback(string ErrorMessage)
    {
        if (ErrorMessage != null)
        {
        }

        return View();
    }

    [HttpPost]
    public ActionResult Feedback(FeedbackForm Model)
    {
        string ErrorMessage;

        //email
        System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
        msg.BodyEncoding = Encoding.UTF8;
        msg.Priority = MailPriority.High;

        msg.From = new MailAddress(Model.Email, Model.Name);
        msg.To.Add("[email protected]");

        msg.Subject = @Resources.Global.Feedback_Email_Title + " " + Model.Company;
        string message = @Resources.Global.Feedback_Email_From + " " + Model.Name + "\n"
                        + @Resources.Global.Feedback_Email + " " + Model.Email + "\n"
                        + @Resources.Global.Feedback_Phone + " " + Model.Phone + "\n"
                        + @Resources.Global.Feedback_Company + " " +  Model.Company + "\n\n"
                        + Model.AdditionalInformation;
        msg.Body = message;
        msg.IsBodyHtml = false;

        //Attachment
        if (Model.ProjectInformation != null && !(String.IsNullOrEmpty(Model.ProjectInformation.FileName)))
        {
            HttpPostedFileBase attFile = Model.ProjectInformation;
            if (attFile.ContentLength > 0)
            {
                var attach = new Attachment(attFile.InputStream, attFile.FileName);
                msg.Attachments.Add(attach);
            }
        }

        SmtpClient client = new SmtpClient("denver.corepartners.local", 55);
        client.UseDefaultCredentials = false;
        client.EnableSsl = false;

        try
        {
            client.Send(msg);
        }

        catch (Exception ex)
        {
            return RedirectToAction("Feedback", "Home", ErrorMessage = "Ошибка при отправке письма, попробуйте позже");
        }

        return RedirectToAction("Feedback", "Home");
    }

and added to the second controller

    /*CareerForm*/
    [HttpGet]
    public ActionResult CareerForm()
    {
        CareerForm model = new CareerForm();

        model.StartNow = true;

        model.EmploymentType = new List<CheckBoxes>
        {
            new CheckBoxes { Text = "полная занятость" },
            new CheckBoxes { Text = "частичная занятость" },
            new CheckBoxes { Text = "контракт" }
        };

        return View(model);
    }


    [HttpPost]
    public ActionResult CareerForm(CareerForm Model)
    {

        string ErrorMessage;

        //curricula vitae to email
        System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
        msg.BodyEncoding = Encoding.UTF8;
        msg.Priority = MailPriority.Normal;

        msg.From = new MailAddress(Model.Email, Model.Name + " " + Model.Surname);
        msg.To.Add("[email protected]");

        msg.Subject = "Анкета с сайта";

        string message = "Имя: " + Model.Name + " " + Model.Surname + "\n"
                        + "Контактный телефон: " + Model.Phone + "\n";

                        if (Model.Adress != null)
                        {
                            message += "Адрес: " + Model.Adress + "\n";
                        }

                        message += "Email: " + Model.Email + "\n"
                        + "Желаемая должность: " + Model.Position;

                        bool check = false;
                        foreach (var item in Model.EmploymentType)
                        {
                            if (item.Checked) check = true;
                        };

                        if (check == true)
                        {
                            message += "\nТип занятости: ";
                            foreach (var item in Model.EmploymentType)
                            {
                                if (item.Checked) message += item.Text + " ";
                            };
                        }
                        else
                        {
                            message += "\nТип занятости: не выбран";
                        }

                        if (Model.StartNow)
                        {
                            message += "\nМогу ли немедленно приступить к работе: да";
                        }
                        else
                        {
                            message += "\nГотов приступить к работе с: " + Model.StartFrom;
                        }

        msg.Body = message;
        msg.IsBodyHtml = false;

        //Attachment
        if (Model.Resume != null && !(String.IsNullOrEmpty(Model.Resume.FileName)))
        {
            HttpPostedFileBase attFile = Model.Resume;
            if (attFile.ContentLength > 0)
            {
                var attach = new Attachment(attFile.InputStream, attFile.FileName);
                msg.Attachments.Add(attach);
            }
        }

        SmtpClient client = new SmtpClient("denver.corepartners.local", 55);
        client.UseDefaultCredentials = false;
        client.EnableSsl = false;

        try
        {
            client.Send(msg);
        }

        catch (Exception ex)
        {
            return RedirectToAction("CareerForm", "Career", ErrorMessage = "Ошибка при отправке письма, попробуйте позже");
        }

        return RedirectToAction("CareerForm", "Career");
    }

But I get an attached file only at the first case, when I send FeedbackForm to email.
For CareerForm I get email, but every time it is without an attachment. I checked in debagger and I saw Model.Resume = null every time, but I dont undestand why.
what's wrong with my code?
Maybe it's bacause I create CareerForm model = new CareerForm(); in [HttpGet] ?
How can I fix that?
UPD Views:
FeedbackForm http://jsfiddle.net/fcnk9/
CareerForm http://jsfiddle.net/9Gz9u/

Upvotes: 0

Views: 217

Answers (1)

davmos
davmos

Reputation: 9577

You need to set enctype = "multipart/form-data" in your Career form, just like you have in your Feedback form...

@using (Html.BeginForm("CareerForm", "Career", FormMethod.Post, new { id = "career-form", @class = "form-horizontal", enctype = "multipart/form-data" }))

For more information as to why, see Why File Upload didn't work without enctype?

Upvotes: 1

Related Questions