Logging Exception to Email

Background
 
Logging the errors of a live application is very important to avoid any inconvenience for the users. In C# to handle exceptions the try, catch and finally keywords are used, so in this article, we will learn how to catch the error and send the error details by Email so developers can fix it as soon as possible.
 
So let us start by creating the application.
 
Use the following procedure to create a web site:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New" - "Web Site..." then select "C#" - ""ASP.NET Empty Web Site"" (to avoid adding a master page).
  3. Provide the project a name such as "ExceptionLoggingToEmail" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer then select "Add New Item" - "Default.aspx" page.
  5. Drag and Drop one GridView to the Default.aspx page. Then the page will look as follows.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5. <title></title>  
  6. </head>  
  7. <body bgcolor="silver">  
  8. <form id="form1" runat="server">  
  9. <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">  
  10. </asp:GridView>  
  11. </form>  
  12. </body>  
  13. </html> 
In the preceding source code, we have taken the one grid view and we try to assign a file as the data source for the grid view that is not available so it can generate the error file not found and we can send these error details to an Email.
 
Now create the class named ExceptionLogging to log the error to Email then write the following code:
 
ExceptionLogging.cs
  1. using System;    
  2. using System.Net.Mail;    
  3. using System.Configuration;    
  4. using System.Net;    
  5. using context = System.Web.HttpContext;  
  6. /// <summary>    
  7. /// Summary description for ExceptionLogging    
  8. /// </summary>    
  9. public static class ExceptionLogging    
  10. {  
  11.     private static String ErrorlineNo, Errormsg, ErrorLocation, extype, exurl, Frommail, ToMail, , Sub, HostAdd, EmailHead, EmailSing;  
  12.     public static void SendErrorTomail(Exception exmail)    
  13.     {  
  14.         try    
  15.         {    
  16.             var newline = "<br/>";    
  17.             ErrorlineNo = exmail.StackTrace.Substring(exmail.StackTrace.Length - 7, 7);    
  18.             Errormsg = exmail.GetType().Name.ToString();    
  19.             extype = exmail.GetType().ToString();    
  20.             exurl = context.Current.Request.Url.ToString();    
  21.             ErrorLocation = exmail.Message.ToString();    
  22.             EmailHead = "<b>Dear Team,</b>" + "<br/>" + "An exception occurred in a Application Url" + " " + exurl + " " + "With following Details" + "<br/>" + "<br/>";    
  23.             EmailSing = newline + "Thanks and Regards" + newline + "    " + "     " + "<b>Application Admin </b>" + "</br>";    
  24.             Sub = "Exception occurred" + " " + "in Application" + " " + exurl;    
  25.             HostAdd = ConfigurationManager.AppSettings["Host"].ToString();    
  26.             string errortomail = EmailHead + "<b>Log Written Date: </b>" + " " + DateTime.Now.ToString() + newline + "<b>Error Line No :</b>" + " " + ErrorlineNo + "\t\n" + " " + newline + "<b>Error Message:</b>" + " " + Errormsg + newline + "<b>Exception Type:</b>" + " " + extype + newline + "<b> Error Details :</b>" + " " + ErrorLocation + newline + "<b>Error Page Url:</b>" + " " + exurl + newline + newline + newline + newline + EmailSing;    
  27.             using (MailMessage mailMessage = new MailMessage())    
  28.             {    
  29.                 Frommail = ConfigurationManager.AppSettings["FromMail"].ToString();    
  30.                 ToMail = ConfigurationManager.AppSettings["ToMail"].ToString();    
  31.                  = ConfigurationManager.AppSettings["word"].ToString();  
  32.                 mailMessage.From = new MailAddress(Frommail);    
  33.                 mailMessage.Subject = Sub;    
  34.                 mailMessage.Body = errortomail;    
  35.                 mailMessage.IsBodyHtml = true;    
  36.                 string[] MultiEmailId = ToMail.Split(',');    
  37.                 foreach (string userEmails in MultiEmailId)    
  38.                 {    
  39.                     mailMessage.To.Add(new MailAddress(userEmails));    
  40.                 }  
  41.                 SmtpClient smtp = new SmtpClient();  // creating object of smptpclient    
  42.                 smtp.Host = HostAdd;              //host of emailaddress for example smtp.gmail.com etc    
  43.                 smtp.EnableSsl = true;    
  44.                 NetworkCredential NetworkCred = new NetworkCredential();    
  45.                 NetworkCred.UserName = mailMessage.From.Address;    
  46.                 NetworkCred.word = ;    
  47.                 smtp.UseDefaultCredentials = true;    
  48.                 smtp.Credentials = NetworkCred;    
  49.                 smtp.Port = 587;    
  50.                 smtp.Send(mailMessage); //sending Email  
  51.             }    
  52.         }    
  53.         catch (Exception em)    
  54.         {    
  55.             em.ToString();   
  56.         }    
  57.     }  
  58. } 
In the code above we have created a SendErrorTomail method that accepts the Exception class reference object and we can call this method from the default.aspx.cs file.
If you are unfamiliar with the procedure to send Email then please refer to the following articles of mine:
Now open the default.aspx.cs page and write the following code to assign the data source to the grid view:
  1. protected void Page_Load(object sender, EventArgs e)    
  2. {           
  3.     try     
  4.     {  
  5.         DataSet ds = new DataSet();    
  6.         ds.ReadXml(Server.MapPath("~/abcdfr.xml"));    
  7.         GridView1.DataSource = ds;    
  8.         GridView1.DataBind();         
  9.     }    
  10.     catch (Exception ex)    
  11.     {    
  12.         ExceptionLogging.SendErrorTomail(ex);    
  13.         Label1.Text = "Some Technical Error occurred,Please visit after some time";    
  14.     }  
  15. }
In the code above, we have used try and catch keywords to handle the exception, first in the try block we are trying to assign the emp.xml as the data source to the grid view that is not available and in the catch block we are calling the method SendErrorTomail of the class ExceptionLogging to log the error by ing the Exception class reference object.
 
Now run the application. The following dummy message we will be shown to the user and the actual error will be logged to Email as:
 
 
 
 Now all the Exception details will be logged to the Email  as:
 
 
 We can see that in the preceding Image all the Exception details are logged to the Email that helps developers to fix the error easily.
 
Notes
  • Download the Zip file from the attachment for the full source code of the application.
  • Make the changes in the web.config file depending on your Email id Credential.
Summary
I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.


Similar Articles