ASP.Net 使用 Respsone.Redirect 取决于电子邮件是否已发送

ASP.Net Using A Respsone.Redirect Depending On If The Email Has Been Sent Or Not

我有一个 4pg 进程,第 3 页是我的确认页。此页面有一个发送和发送电子邮件的按钮。然后,无论电子邮件是否发送,我都有一个 response.redirect。我想做的是,如果电子邮件已发送,则转到下一页,但如果发送失败,则在页面上显示错误,而不是重定向。

不确定如何执行此操作。我的代码是

protected void pg3button_Click(object sender, EventArgs e)
        {
            try
            {
                //Create the msg object to be sent
                MailMessage msg = new MailMessage();

                //Add your email address to the recipients
                msg.To.Add("test@test.com");

                //Configure the address we are sending the mail from
                MailAddress address = new MailAddress("test@test.com");
                msg.From = address;

                //Append their name in the beginning of the subject
                msg.Subject = "Enquiry";

                msg.Body = Label1.Text + " " + Session["pg1input"].ToString()
                            + Environment.NewLine.ToString() +
                            Label2.Text + " " + Session["pg1dd"].ToString()
                            + Environment.NewLine.ToString() +
                            Label3.Text + " " + Session["pg2"].ToString();

                //Configure an SmtpClient to send the mail.
                SmtpClient client = new SmtpClient("smtp.live.com", 587);
                client.EnableSsl = true; //only enable this if your provider requires it

                //Setup credentials to login to our sender email address ("UserName", "Password")
                NetworkCredential credentials = new NetworkCredential("test@test.com", "Password");
                client.Credentials = credentials;

                //Send the msg
                client.Send(msg);

                //Display some feedback to the user to let them know it was sent
                lblResult.Text = "Your message was sent!";

                //Clear the form
                //txtName.Text = "";
                //txtMessage.Text = "";
            }
            catch
            {
                //If the message failed at some point, let the user know
                lblResult.Text = "Your message failed to send, please try again.";
            }
                Response.Redirect("/Session/Pg4.aspx");                
        }

Response.Redirect("/Session/Pg4.aspx"); 移动到 try 块内。 您只想在快乐的路径中重定向(无一例外)