Sending emails withing your asp.net application

written by Dave on Saturday, July 19 2008

A very handy feature to have in your asp.net application is an email class that you can call into whenever your need to send an email. Here are some simple steps to create a static class for sending out emails.

I started out by creating a class called Email.cs in my app_code folder and added in the required reference for sending email:

using System.Net.Mail;

I then jumped right into building out the class. The code should be pretty self expanitory but you will notice that I added in a little complexity so that if my primary SMTP server was unavailable, a secondary server would be tried. This secondary server may not be realistic for your scenario.

 

public static void SendEmail(string to, string from, string subject, string body)
 {
  //create the mail message
  try
  {
   MailMessage mail = new MailMessage(from, to);

   mail.Subject = subject;
   mail.Body = body;

   //MailAddress blindCopy = new MailAddress("yourname@yourdomain.com");   //Enter an email if you want an auto BCC to be sent on each email.
   //mail.Bcc.Add(blindCopy);

   SmtpClient smtp = new SmtpClient("000.000.000.000");     //Enter the IP of your SMTP server

   smtp.Send(mail);
  }
  catch (Exception ex)
  {
  try
   {
    //Attempt 2 on second mail server
    MailMessage mail = new MailMessage(from, to);

    mail.Subject = subject;
    mail.Body = body;

    MailAddress blindCopy = new MailAddress("yourname@yourdomain.com");   //Enter an email if you want an auto BCC to be sent on each email.
    mail.Bcc.Add(blindCopy);

    SmtpClient smtp = new SmtpClient("111.111.111.111");    //Enter the IP of your secondary SMTP server

    smtp.Send(mail);

  }
   catch
   {
    //An Error Occurred
    throw new Exception(ex.Message, ex.InnerException);
   }
  }
 }

 You can also utilize a class like this for handling error emails that you application sends out. Check out this post for more information on trapping errors and generating email notifications.

Similar Posts

  1. Error Handling Within Your Asp.Net Web Application
  2. ASP Error Handling
  3. Asp.Net Checkbox Validation

Comments are closed

Options:

Size

Colors