Friday, January 25, 2008

Sending E-Mails in ASP.Net

using System.Net.Mail;

public void SendPageErrorMailToAdmin(string ErrorPageName, string ExceptionMessage)
{

string _to = System.Configuration.ConfigurationManager.AppSettings ["SiteMasterEmail"];
string _from = System.Configuration.ConfigurationManager.AppSettings ["AdminEmail"];
//string _to = System.Configuration.ConfigurationManager.AppSettings ["ContactEmail"];


MailAddress from = new MailAddress( _from, "My Website Admin");
MailAddress to = new MailAddress( _to, "My SiteMaster");
MailMessage msg = new MailMessage( from, to);

msg.Body = "Dear SiteMaster, An Exception Has Been Found !" + Environment.NewLine;
msg.Body += "=============================================" + Environment.NewLine;
msg.Body += Environment.NewLine;

//=====Testing Lines, Not To Be Included in the Main Site.
//msg.Body += "//=====Testing Line, Not To Be Included in the Main Site." + Environment.NewLine;
//msg.Body += "(From " + _from + " To " + _to + ")" + Environment.NewLine;


msg.Body += Environment.NewLine;
msg.Body += "ExceptionPage : " + ErrorPageName + "." + Environment.NewLine;
msg.Body += Environment.NewLine;
msg.Body += Environment.NewLine;
msg.Body += "Exception : " + Environment.NewLine;
msg.Body += ExceptionMessage + ".";
msg.Body += Environment.NewLine;
msg.Body += Environment.NewLine;
msg.Body += Environment.NewLine;
msg.Body += "Needs To Be Corrected Immediately." + Environment.NewLine;
msg.Body += "Thanks" + Environment.NewLine;

msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.Subject = "An Exception on " + ErrorPageName + " page.";
msg.Priority = MailPriority.High;
SmtpClient smtpObj = new SmtpClient("127.0.0.1");
smtpObj.Send(msg);
}


-
ShriKrishna Bhardwaj , With ASP.Net, SQL Server, Javascript

2 comments:

Jai Rajputana said...

You forgot to mention to call this function from global.asax of each project to track all the application errors and pass in the filepath and inner exception string only when not in debug mode.
Code:
protected void Application_Error(Object sender, EventArgs e) {
#if !DEBUG
SendPageErrorMailToAdmin(System.Web.HttpContext.Current.Request.Url.AbsoluteUri, System.Web.HttpContext.Current.Server.GetLastError().InnerException.ToString());
#endif
}


~nsj

Shrikrishna BHARDWAJ said...

thanks deep ...

but i've just written the code to send an e-mail using an example of errors in some page ...

its all up to the programmer that from where he wants to call the method ..