0

Catch block used whenever there is an exception while using smtp port,but it will throw exception thats fine,it will take a very long time and also the exception message will be directly shown in the code itself,requirement is to display an error message while executing in the localserver and shouldnot come to the code. It should throw exception whenever the server is down or invalid email Id or change in smtp port,Conclusion is the error message should not come directly to the code.It should display an error message and stop the application which should not hang.

 protected void Button2_Click(object sender, EventArgs e)
{

    //string vv;
    //vv = (string)Session["FID"];
    DateTime sdt = DateTime.Today;

    SqlCommand cmd4 = new SqlCommand();

    int flag=0;


   String test = DateTime.Now.ToString("dd.MM.yyy");
   for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
   {

       string toemail = GridView1.Rows[i].Cells[2].Text;
       string FID1 = GridView1.Rows[i].Cells[0].Text;
       GridViewRow row = GridView1.Rows[i];
       CheckBox Ckbox = (CheckBox)row.FindControl("CheckBoxMark1");
       if (Ckbox.Checked == true)
       {

           sendMail(toemail);
           flag = 1;
           //ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Email send Succesfully')</script>");
       }

       if (flag == 1)
       {
           ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Email sent  on " + test + "')</script>");

           cn.Open();
           //cmd4.CommandText = "Insert into TrackingFaculty_det  (EmailsentDate)  values (@EmailsentDate) WHERE FID=@FID";
           cmd4.CommandText = "update TrackingFaculty_det SET EmailsentDate=@Email WHERE FID=@FID  ";
           cmd4.CommandType = CommandType.Text;
           cmd4.Connection = cn;

           cmd4.Parameters.Clear();


           cmd4.Parameters.Add("@Email", SqlDbType.DateTime, 8);
           cmd4.Parameters["@Email"].Value = sdt;
           cmd4.Parameters.Add("@FID", SqlDbType.VarChar, 10);
           cmd4.Parameters["@FID"].Value = FID1;
           cmd4.ExecuteNonQuery();
           cn.Close();
           log.Debug("Info : Insert the Email Sent Date of the faculty");
       }
       else
       {
           ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Email cannot be sent')</script>");
       }




   }
   log.Debug("Info : Function used to send mail");
}

public void sendMail(String toemail)
{


    try
    {


        MailMessage mail = new MailMessage();
        mail.To.Add(toemail);
        mail.From = new MailAddress("manipal.mcis1@gmail.com");
        mail.Subject = "Remember Mail";
        // string Body = "Please update profile";
        //mail.Body = Body;
        mail.Body = "  Dear Sir/Madam \n\n\n Please update your profile. . \n\n\n Thanks & Regards \n\n\n MCIS,Manipal.";
        //mail.Body = "<html><body> <h2" + "align=center>Dear Sir/Madam" + "</h2> Please update ur profile</body></html>";
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 584;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new System.Net.NetworkCredential("manipal.mcis1@gmail.com", "manipal15");
        smtp.EnableSsl = true;
        smtp.Send(mail);


    }
catch (SmtpException ex)
    {

   string msg = "Mail cannot be sent:";
        msg += ex.Message;
        log.Debug("Error: Inside catch block of Mail sending");
        log.Error("Error msg:" + ex);
        log.Error("Stack trace:" + ex.StackTrace);


        throw new Exception(msg);

    }

This also arrises with another issue that is whenever it enters for loop its executing the
send(tomail) function even if it is invalid along with this ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Email sent on " + test + "')</script>"); line is also executed at every instance.i need to make this work out only when valid EmailID and proper smtp port is available.

Shreyas Achar
  • 1,407
  • 5
  • 36
  • 63

2 Answers2

2

Try these lines of code it will work

protected void Button2_Click(object sender, EventArgs e)
{

    //string vv;
    //vv = (string)Session["FID"];
    DateTime sdt = DateTime.Today;

    SqlCommand cmd4 = new SqlCommand();

    int flag=0;


   String test = DateTime.Now.ToString("dd.MM.yyy");
   for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
   {

       string toemail = GridView1.Rows[i].Cells[2].Text;
       string FID1 = GridView1.Rows[i].Cells[0].Text;
       GridViewRow row = GridView1.Rows[i];
       CheckBox Ckbox = (CheckBox)row.FindControl("CheckBoxMark1");
       if (Ckbox.Checked == true)
       {

           sendMail(toemail);
           flag = 1;
           //ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Email send Succesfully')</script>");
       }

       if (flag == 1)
       {
           //ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Email sent  on " + test + "')</script>");

           cn.Open();
           //cmd4.CommandText = "Insert into TrackingFaculty_det  (EmailsentDate)  values (@EmailsentDate) WHERE FID=@FID";
           cmd4.CommandText = "update TrackingFaculty_det SET EmailsentDate=@Email WHERE FID=@FID  ";
           cmd4.CommandType = CommandType.Text;
           cmd4.Connection = cn;

           cmd4.Parameters.Clear();


           cmd4.Parameters.Add("@Email", SqlDbType.DateTime, 8);
           cmd4.Parameters["@Email"].Value = sdt;
           cmd4.Parameters.Add("@FID", SqlDbType.VarChar, 10);
           cmd4.Parameters["@FID"].Value = FID1;
           cmd4.ExecuteNonQuery();
           cn.Close();
           log.Debug("Info : Insert the Email Sent Date of the faculty");
       }




   }
   log.Debug("Info : Function used to send mail");
}

public void sendMail(String toemail)
{


    try
    {


        MailMessage mail = new MailMessage();
        mail.To.Add(toemail);
        mail.From = new MailAddress("manipal.mcis1@gmail.com");
        mail.Subject = "Remember Mail";
        // string Body = "Please update profile";
        //mail.Body = Body;
        mail.Body = "  Dear Sir/Madam \n\n\n Please update your profile. . \n\n\n Thanks & Regards \n\n\n MCIS,Manipal.";
        //mail.Body = "<html><body> <h2" + "align=center>Dear Sir/Madam" + "</h2> Please update ur profile</body></html>";
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new System.Net.NetworkCredential("manipal.mcis1@gmail.com", "manipal15");
        smtp.EnableSsl = true;
        smtp.Send(mail);


    }
    catch (SmtpException ex)
    {


        string msg = "Mail cannot be sent because of the server problem:";
        msg += ex.Message;
        log.Debug("Error: Inside catch block of Mail sending");
        log.Error("Error msg:" + ex);
        log.Error("Stack trace:" + ex.StackTrace);

        Response.Write(msg);
        //throw new Exception(msg);

    }
0

The time that it needs is the time it needs to "understand" that something is not ok (tehre could different reasons that smtp fails, naturally) .

In you concrete code I see that you re - raise an exception, which is according to the your requirements is not what you want, so probabbly better solution could be:

    catch (SmtpException ex)
    {

       string msg = "Mail cannot be sent:";
         msg += ex.Message;
         log.Debug("Error: Inside catch block of Mail sending");
         log.Error("Error msg:" + ex);
         log.Error("Stack trace:" + ex.StackTrace);


         SendAsyncMessage(msg);//just an example

    }

For client side notification you can use whatever you want. There are different libraries for that:

and so on ...

If this is not what you're asking for, please clarify.

Tigran
  • 61,654
  • 8
  • 86
  • 123
  • Thats looks good but if i use `MessageBox` inside catch i think it will show `The name MessageBox` doesnot exixts in current content` – Shreyas Achar Oct 22 '13 at 06:47
  • @SatwikMn: considering that SMTP execution is async in your case, you have to wait for response on client side, and in case of exception return just mesagge (OK, FAIL), and *client* shows a message to the user. – Tigran Oct 22 '13 at 06:56
  • So it will take around 25-30 seconds to handle the exception?.you dont think its a very long time to handle the exception? – Shreyas Achar Oct 22 '13 at 06:59
  • @SatwikMn: if the SMTP takes so much time to figure out that it fails, it's probably sysadmin issue more then code. But that may not even a problem, if a user notified about failure in some way. – Tigran Oct 22 '13 at 07:04
  • What if i used `Response.Writeline(msg);` instead of `SendAsyncMessage(msg);` – Shreyas Achar Oct 22 '13 at 08:02