wayne on March 3, 2008
You will ultimately need to send emails from your web application. So how do you easily do this? Here's one method that is really simple that I use consistently throughout my projects. Please keep in mind there are several ways to wrapper the 'send email' functionality. I choose a static class that I simply drop in each project because it gives me portability across several different code bases and projects.
The following code can be placed into a C# class file and used right away:
using System;
using System.Net.Mail;
/// <summary>
/// Provides functionality for sending emails
/// </summary>
public static class Email
{
/// <summary>
/// Sends an email via the supplied server
/// </summary>
/// <param name="to">The address you wish to send to</param>
/// <param name="from">The address the email will come from</param>
/// <param name="subject">The subject of the email</param>
/// <param name="body">The body content of the email</param>
/// <param name="smtpserver">The SMTP server to send the email through (localhost or other)</param>
public static void SendEmail(string to, string from, string subject, string body, string smtpserver)
{
MailMessage mail = new MailMessage(from, to, subject, body);
mail.IsBodyHtml = true;
SmtpClient smtp = null; try
{ smtp = new SmtpClient(smtpserver);
smtp.Send(mail);
}
catch { throw; }
finally
{
mail.Dispose();
}
}
}
The class contains only a single procedure named appropriately enough, SendEmail. The procedure will throw any errors generated during the send mail process. I assume that we can create a new MailMessage object all day long without any errors being generated. The only sticky points are if you are unable to connect to the smtp server and actually send an email through it.
The mail.IsBodyHtml property can be refactored up to an input parameter if desired. Hope this helps someone out there! Let me know your thoughts or how this can be improved.