sending Logging error to Email

Updated : Oct 20, 2019 in Articles

How to sending Logging errors to Email in MVC

In this article, we will learn How to sending Logging errors to Email in MVC


this given below code is useful for finding the exception in login time if any exception raised at login time that will automatically send to your mail-id

if you want to store the real-time exceptions at login time you will save these exceptions at your database also

Sending Logging errors to Email

In your application inside the login function, you will set the Session[“UserName”] =obj.User; and the create the LogError() function, through HttpContext.Current.Session[“UserName”] get the username

you will format an exception Message like which user is logged in and when that exception is raised (date) this all thing you will concatenate in one string and then Send to errors to Mail

Follow given code helpful for sending Logging errors to Email in MVC

     public static void LogError(Exception ex)
            string message = "";

            message += "Logged in User : " + HttpContext.Current.Session["UserName"];
            message += Environment.NewLine;
            message += string.Format("Date and Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
            message += Environment.NewLine;        
            message += "-----------------------------------------------------------";
            message += Environment.NewLine;
            message += string.Format("Message: {0}", ex.Message);
            message += Environment.NewLine;
            message += string.Format("StackTrace: {0}", ex.StackTrace);
            message += Environment.NewLine;
            message += string.Format("Source: {0}", ex.Source);
            message += Environment.NewLine;
            message += string.Format("TargetSite: {0}", ex.TargetSite.ToString());
            message += Environment.NewLine;
            message += "-----------------------------------------------------------";
            message += Environment.NewLine;

            if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/ErrorLog/")))

            string path =HttpContext.Current.Server.MapPath("~/ErrorLog/ErrorLog.txt");
            using (StreamWriter writer = new StreamWriter(path, true))

you will pass error message as a parameter to SendingErrorToMail() method and then enter your email id, port, password, Host in Smptclient see given below code

 private static void SendErrorToMail(string errorMessage)
            string ToAddress = ConfigurationManager.AppSettings["MailAddress"];
            StringBuilder errorMsg = new StringBuilder();
            MailAddress to = new MailAddress(ToAddress);
            MailAddress from = new MailAddress("yourmail");
            MailMessage message = new MailMessage(from, to);
            message.Subject = "Error Message";
            message.Body = errorMessage;
            message.BodyEncoding = Encoding.UTF8;
            message.IsBodyHtml = true;

            SmtpClient client = new SmtpClient();
            client.UseDefaultCredentials = true;
            client.Credentials = new System.Net.NetworkCredential("yourmail", "password");
            client.Port = 587; // 
            client.Host = "hosting mail";
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.EnableSsl = true;
            //Add this line to bypass the certificate validation
            System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (object s,
                    System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                    System.Security.Cryptography.X509Certificates.X509Chain chain,
                    System.Net.Security.SslPolicyErrors sslPolicyErrors)
                return true;
            catch (Exception ex)

Saving logging Exceptions In your database

After sending these logging error message to Email we will save these errors in the database

step 1:

Create a table in your database table name like LoginException by using given below SQL Query

CREATE TABLE [dbo].[LoginException](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[UserName] [nvarchar](15) NOT NULL,
	[ExceptionMessage] [ntext] NULL,
	[ExceptionCreatedDate] Datetime NULL,

Step 2:

right-click on model folder create a class name like LoginException see the given below snippet code

public class LoginException
        public int ID { get; set; }
        public string UserName { get; set; }
        public string ExceptionMessage { get; set; }
        public DateTime ExceptionCreatedDate { get; set; }

step 3:

Right-click on your project Add Ado.Net entity data model or you will use

if you are using Ado.Net entity data model use given below snippet code for saving logging errors in your database

    public class Loginrepo
        TestDBEntities context = new TestDBEntities();
        public void SaveLoginExceptions(string username,string exceptionmessage)
            LoginException obj = new LoginException();
            obj.UserName = username;
            obj.ExceptionMessage = exceptionmessage;
            obj.ExceptionCreatedDate = DateTime.Now;

you will call this SaveLoginExceptions() method before sending the error to mail and pass username, exception message as parameters

Loginrepo obj=new Loginrepo();

if you are using in your application Add given snippet code for saving logging exceptions in MVC

 public static string InsertIntoTable(string Query)
            SqlConnection con = Functions.con();
			SqlCommand com = new SqlCommand();
			com.Connection = con;
			if (Query.Length>0)
				com.CommandText =Query;
				string IdentityColumnValue= com.ExecuteScalar().ToString();			
				return IdentityColumnValue;
				return "";			

call this InsertIntoTable() Ado.Net Db helper method for saving logging error and pass the given below query as a string format

 string qry = "insert into LoginException(UserName,ExceptionMessage,ExceptionCreatedDate)values(" + HttpContext.Current.Session["UserName"] + "," + Exceptionmessage + "," + DateTime.Now + ")";


sending Logging error to Email
sending Logging error to Email

Latest posts by DuttaluruVijayakumar (see all)
Like Love Haha Wow Sad Angry

Notify of
Newest Most Voted
Inline Feedbacks
View all comments
Free Samples
February 1, 2020 2:40 am

Hi there, I discovered your web site by means of Google even as searching for a related topic, your web site got here up, it looks good. I have bookmarked it in my google bookmarks.

Lindsy Yokel
April 8, 2020 2:02 pm

Saved as a favorite!, I like your blog!

Eunice Meineke
April 9, 2020 3:01 pm

Bookmarked!, I like your web site!

Karmen Dewolfe
April 25, 2020 10:26 pm

Bookmarked!, I like your website!

Agustin Magone
Agustin Magone
April 28, 2020 5:27 am

Bookmarked!, I like your web site!

Would love your thoughts, please comment.x