Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Sending emails using asp.net - Part 77

Suggested Videos
Part 74 - Logging exceptions as information entry type in windows eventviewer
Part 75 - Logging exceptions to database
Part 76 - Customizing asp.net exception Logging

In the previous sessions of this video series, we have discussed about logging exceptions to database and to the windows eventviewer. In this session, sending an email to the development team or administrator along with logging exceptions.

To compose the email message, use MailMessage calss. To send the email use, SmtpClient class. Both of these classes are present in System.Net.Mail namespace.



public static void SendEmail(string emailbody)
{
    // Specify the from and to email address
    MailMessage mailMessage = new MailMessage("from_email@gmail.com", "To_Email@gmail.com");
    // Specify the email body
    mailMessage.Body = emailbody;
    // Specify the email Subject
    mailMessage.Subject = "Exception";

    // Specify the SMTP server name and post number
    SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
    // Specify your gmail address and password
    smtpClient.Credentials = new System.Net.NetworkCredential() 
    { 
        UserName = "from_email@gmail.com", Password = "your_password"
    };
    // Gmail works on SSL, so set this property to true
    smtpClient.EnableSsl = true;
    // Finall send the email message using Send() method
    smtpClient.Send(mailMessage);
}



SendEmail() method can then be called in our Logger class. Pass in the exception string as an input parameter.
SendEmail(sbExceptionMessage.ToString());

If you want the capability of sending emails to be configurable, add the following key in web.config.
<appSettings>
  <add key="SendEmail" value="true"/>
</appSettings>

Read "SendEmail" key from web.config. If SendEmail is set to true only then, send the email.
string sendEmail = ConfigurationManager.AppSettings["SendEmail"];
if (sendEmail.ToLower() == "true")
{
    SendEmail(sbExceptionMessage.ToString());
}

In this video we discussed about sending emails using gmail smtp server and credentials. In reality organisations have their own SMPT server. If you want to send emails using your own SMTP server, use the respective smtp server address and credentials.

3 comments:

  1. hi sir ,sending mail from gmail , u have covered, incase if the mail is to send from other than gmail ,then the same should be followed?pls clarify my doubt...

    ReplyDelete
  2. You are the best teacher i never seen, your way to teach is excellent
    Thanks a lot to having time to prepare these course, from DRC

    ReplyDelete
  3. bravo u r the best teacher of the world
    tnx for ur tutorials

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.