使用Webforms前端时出现C#CodeBehind错误

时间:2017-10-04 21:51:50

标签: c#

我正在尝试了解如何使用C#CodeBehind生成带附件的电子邮件。我希望网页使用FileUpload控件或类似的东西来选择网络上的文件。

我得到一个“无法找到路径的一部分'E:\ Web Sites \ myNet \ Ztest \ TrailerPics \'。”

我想知道我是否走在正确的道路上......或者是否有更好的方法。

Thx任何帮助~j

这是我的代码:

protected void Button1_Click(object sender, EventArgs e)
    {
        //Get file names from the fileUpload control
        var fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
        var fileName2 = Path.GetFileName(FileUpload2.PostedFile.FileName);
        var fileName3 = Path.GetFileName(FileUpload3.PostedFile.FileName);


        //Code block to send email with keyed data
        try
        {
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("DoNotReply@smiley.com");
            mail.To.Add("guy.smiley@sesamestreet.com");
            mail.Subject = ("IMG");
            mail.IsBodyHtml = true;

            var client = new SmtpClient("mailout.smiley.com", 25);
            string htmlBody;

            htmlBody = string.Format("Email Testing for attaching an image");

            mail.Body = htmlBody;

            //Create the instance of attachments by using the mapped path concatenated with the file name
            Attachment addon = new Attachment(Server.MapPath("~/TrailerPics/" + fileName));
            Attachment addon2 = new Attachment(Server.MapPath("~/TrailerPics/" + fileName2));
            Attachment addon3 = new Attachment(Server.MapPath("~/TrailerPics/" + fileName3));

            //Add the attachments as long as the fileUpload control has a file selected
            if (FileUpload1.PostedFile.FileName != "")
            {                    
                mail.Attachments.Add(addon);                    
            }

            if (FileUpload2.PostedFile.FileName != "")
            {                    
                mail.Attachments.Add(addon2);                    
            }

            if (FileUpload3.PostedFile.FileName != "")
            {                   
                mail.Attachments.Add(addon3);                   
            }

            //Send mail
            client.Send(mail);

            //Notify that email was sent
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Email Sent!')", true);

            //Close all connections to the files 
            if (FileUpload1.PostedFile.FileName != "")
            {
                addon.Dispose();
            }

            if (FileUpload2.PostedFile.FileName != "")
            {
                addon2.Dispose();
            }

            if (FileUpload3.PostedFile.FileName != "")
            {
                addon3.Dispose();
            }

        }

        catch(Exception ex)
        {
            //inform user that the email failed
            errorLabel.Text = "Something went wrong with the email : " + ex.Message;
        }
    }

0 个答案:

没有答案