Sending Error/Exception Reports via Email in ASP.net and C# (C-sharp)
Firstly, enter this code in to the appropriate area, within global.asax file:
NOTE: Sorry about the poor formating (Blogger doesn't seem to handle code very well).
void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
System.Text.StringBuilder sbMessage = new System.Text.StringBuilder();
sbMessage.Append("<dl style=\"font-face: Arial; font-weight: normal; font-size: 13px; line-height: 16px;\">");
sbMessage.Append("<dt style=\"font-weight: bold;\">Source:</dt>");
sbMessage.AppendFormat("<dd>{0}</dd>", exception.Source);
sbMessage.Append("<dt style=\"font-weight: bold;\">Date and Time:</dt>");
sbMessage.AppendFormat("<dd>{0}</dd>", DateTime.Now.ToString("MM/dd/yyyy h:mm tt"));
sbMessage.Append("<dt style=\"font-weight: bold;\">Message:</dt>");
sbMessage.AppendFormat("<dd>{0}</dd>", exception.Message);
sbMessage.Append("<dt style=\"font-weight: bold;\">Stack Trace:</dt>");
sbMessage.AppendFormat("<dd>{0}</dd>", exception.StackTrace);
sbMessage.Append("</dl>");
using (System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage())
{
mailMessage.From = new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["emailWebsite"].ToString());
mailMessage.To.Add(new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["emailInformation"].ToString()));
mailMessage.Subject = "[ERROR] Unhandled Exception from the Website";
mailMessage.Body = sbMessage.ToString();
mailMessage.IsBodyHtml = true;
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
smtpClient.Host = ConfigurationManager.AppSettings["mailServerOutgoing"].ToString());
smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["emailWebsite"].ToString(), ConfigurationManager.AppSettings["emailWebsitePassword"].ToString());
smtpClient.Send(mailMessage);
}
}
Once this is completed, and modified to specification, we must add the following definitions to the web.config (in the appSettings element):
<appsettings>
<add key="mailServerOutgoing" value="mail.your-server-address.com">
<add key="emailWebsite" value="mailer@your-server-address.com">
<add key="emailWebsitePassword" value="your-mailer-password">
<add key="emailInformation" value="receiving@your-server-address.com">
</appsettings>
This allows us to keep important information, such as email accounts and passwords, separate from the codebehind file, and is thus moderately more secure.
And that is all there is to it! All we ask is that if you use our code, just take a few moments and digg this entry using the addThis panel below. Thank you.
...

