Send ASP.NET formatted errors details via Email.

Exception/Error is common scenario in any application. In ASP.NET, there many ways to handle those errors or exception, for example, when an error or exception occurred in ASP.NET application, system is going to send formatted error message to specified developers or team mentioned in the email list. The difference will be the body of email will contain exactly same formatted error ASP.NET generated to display the error or exception details when occurred. For example,

But when an ASP.NET application goes into life, user should not experience to see the above error page where they should see custom error page which easy to understand. More information about is in here.

So in here, this test application will display default error page when there is an error occurred in the system and send an email formatted like above image. 

To do that need to add void Application_Error(object sender, EventArgs e) method into Global.asax.cs file,  the code block is,

    void Application_Error(object sender, EventArgs e)
            HttpUnhandledException httpUnhandledException = new HttpUnhandledException(Server.GetLastError().Message, Server.GetLastError());
So GetHtmlErrorMessage() method of HttpUnhandledException class will do all the formatting stuff.
The code block to send email is below,
        private static void SendEmailWithErrors(string result)
                MailMessage Message = new MailMessage();
                Message.To = "To address";
                Message.From = "FROM addressd";
                Message.Subject = "Exception raised";
                Message.BodyFormat = MailFormat.Html;
                Message.Body = result;
                SmtpMail.SmtpServer = "SMTP Sever Address";
            catch (System.Web.HttpException ehttp)
                // Write o the event log.
To test it there is button on page which manually trigger an exception, the code for button is as below,
        protected void btnError_Click(object sender, EventArgs e)
        {            throw new Exception("This Exception is raised to test");
So now the system will display default error page when an exception occurred and send email with formatted exception details as below,
Default Error page,

And an email with formatted exception details,


  1. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article. Dot Net Training in chennai | Dot Net Training in velachery


  2. Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. dot net training in velachery | dot net training in chennai