简体   繁体   中英

Exception Handling While send a mail using smtp Port

protected void Button2_Click(object sender, EventArgs e) {        
    //string vv;
    //vv = (string)Session["FID"];
    DateTime sdt = DateTime.Today;
    SqlConnection cn1 = new SqlConnection();
    SqlCommand cmd4 = new SqlCommand();

    cn1.ConnectionString = @"Data Source=BOPSERVER;Initial Catalog=Project;Integrated Security=True";

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

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

           cn1.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 = cn1;

           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();
           cn1.Close();
       }                      
   }
}

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 (Exception ex) {            
        //System.ArgumentException argx = new System.ArgumentException("There is some problem in sending mail please try again later");
        //throw argx;
        //Console.WriteLine("There is some problem in sending mail please try again later", ex.Message);
        Response.Write(ex.ToString());
    }

These lines of codes enables to send a mail using smtp port,Its working fine. Looking through the other prospective there might be some exceptions where in there may be possibility of inputting Dummy email like abc@gmail.com or there might be some server issues where in mail cannot be sent at that particular time or there might be some other exception, In Those instance exception handling functions must be come into act and should display a pop-up-window or some error message such as mail cannot be sent, is there any possibilities?

The SMTP server level problems should be handled using SmtpException .
So you can modify your catch block as follows

 catch (SmtpException ex)
 {    
     Response.Write(ex.ToString());
 }

However, the mailboxes problems are sometimes not handled by SmtpException.
For this you can use SmtpFailedRecipientException which is used to wrap errors reported from an individual mailbox. This exception contains a StatusCode property of type enum that will tell us the exact cause of the error.

Please refer following catch block

catch (SmtpFailedRecipientException ex)        
{
      SmtpStatusCode statusCode = ex.StatusCode;    

      if (statusCode == SmtpStatusCode.MailboxBusy ||
          statusCode == SmtpStatusCode.MailboxUnavailable ||
          statusCode == SmtpStatusCode.TransactionFailed)
      {                   
           // Display message like 'Mail box is busy', 'Mailbox is unavailable' or 'Transaction is failed'
      }
      else
      {  
           throw;
      }
 }

You can handle individual errors using this

You can simply add an <asp:Label> over/under GridView and in case of excepetion set its Text to error message:

<asp:Label ID="lblMsg" runat="server"></asp:Label>

..

try{
    sendMail(toemail);
}
catch(Exception ex){
    lblMsg.Text = ex.Message; // or whatever message you want to show
    lblMsg.ForeColor = Color.Red // Red shows error
}

...

public void sendMail(String toemail){

    try{
        ...
    }
    catch(Exception ex){
        throw ex; // Don't use Response.Write
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM