附件未附加到电子邮件asp.net mvc

时间:2013-05-30 06:40:41

标签: asp.net-mvc asp.net-mvc-4

我的mvc网站上有两个表单,FeedbackForm和CareerForm。我需要将两个表单发送到同一封电子邮件。我为我的表单和两个视图创建了两个模型,然后我在第一个控制器中添加了

    /*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("tayna-anita@mail.ru");

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

并添加到第二个控制器

    /*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("tayna-anita@mail.ru");

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

但是,当我将FeedbackForm发送到电子邮件时,我只在第一种情况下获得附件 对于CareerForm,我收到电子邮件,但每次都没有附件。 我检查了debagger,每次都看到Model.Resume = null,但我不明白为什么 我的代码有什么问题?
也许这是因为我在CareerForm model = new CareerForm();中创建了[HttpGet]? 我该如何解决? 的 UPD 浏览次数:
FeedbackForm http://jsfiddle.net/fcnk9/
CareerForm http://jsfiddle.net/9Gz9u/

1 个答案:

答案 0 :(得分:1)

您需要在“职业表”中设置enctype = "multipart/form-data",就像您在反馈表中一样......

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

有关原因的详细信息,请参阅Why File Upload didn't work without enctype?