添加附件到电子邮件asp.net mvc 4

时间:2013-05-22 12:07:10

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

我的网站上有反馈表单,我的表单中有<input type="file">,因此有时需要在电子邮件中添加附件。
我在表单中创建了<input type="file">

 @Html.TextBoxFor(model => model.ProjectInformation, null, new { type = "file", @class = "input-file" }) 

然后在我的控制器中创建电子邮件并尝试添加附件

    [HttpPost]
    public ActionResult Feedback(FeedbackForm Model)
    {
        System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
        msg.BodyEncoding = Encoding.UTF8;

        msg.From = new MailAddress("test@mail.ru", @Resources.Global.Feedback_Email_Title);
        msg.To.Add("tayna-anita@mail.ru");

        string message = @Resources.Global.Feedback_Name + ": " + 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)
        {
            HttpPostedFileBase attFile = Model.ProjectInformation;
            int attachFileLength = attFile.ContentLength;
            if (attachFileLength > 0)
            {
                string strFileName = Path.GetFileName(Model.ProjectInformation.FileName);
                Model.ProjectInformation.SaveAs(Server.MapPath(strFileName));
                Attachment attach = new Attachment(Server.MapPath(strFileName));                   
                msg.Attachments.Add(attach);
                string attach1 = strFileName;
            }
        }

        SmtpClient client = new SmtpClient("smtp.mail.ru", 25);
        client.UseDefaultCredentials = false;
        client.EnableSsl = false;

        try
        {
            client.Send(msg);
        }

        catch (Exception ex)
        {
        }

        FeedbackForm tempForm = new FeedbackForm();
        return View(tempForm);
    } 

但我想我需要在发送后删除附件,并尝试在此处添加代码

        try
        {
            client.Send(msg);
            if (attach1 != null)
            File.Delete(Server.MapPath(attach1));
        }

但我犯了一些错误

enter image description here

enter image description here

我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:1)

您应该在if (Model.ProjectInformation != null)

之前声明变量

这样的事情:

    string attach1;
    if (Model.ProjectInformation != null)
    {
        . . .
        if (attachFileLength > 0)
        {
            . . .
            attach1 = strFileName;
        }
    }