Jerald.Net
A little VB.Net, SQL, and whatever else comes to mind...

VB.Net Email Wrapper Class

Introduction

System.Net.Mail is easy to use, so why would I want to have a wrapper for it?

I have often found myself writing this code over and over again. Each time its different and managing multiple version of the same functionality across projects is not very efficient. Consistent code is always easier to maintain.

Background

This wrapper class was the outcome of a discussion on how to encapsulate some common features used in sending email. The environment had multiple SMTP gateways, and it was nice to have the From address to always be supplied under the context of the current account executing the code. Additionally, having the ability to send email asynchronously was important to allow applications to be more responsive.

One note to be mindful of when using the SendMessageAsync method is that if the spawning thread exits prior to the async thread, the email will not be sent.

Features

The Email wrapper class has the following features:

  • Ability to send synchronously or asynchronously
  • Event handler to listen for asynchronous updates
  • MailAddressCollections for To, CC, and Bcc
  • AttachmentCollection for attachments
  • Enumeration of known SMTP gateways

Usage Examples

Simple Synchronous Example:

Try
    'Get an Email object
    Dim emailObject As New Utilities.Email()
    Dim emailSubject As String = String.Empty
    Dim emailBody As New StringBuilder()
      emailSubject = "Random Subject"
    emailBody.Add("I now have a body")
 
    'Set the values
    emailObject.Priority = Email.EmailPriority.High
    emailObject.Body = emailBody.ToString()
    emailObject.Subject = emailSubject
    'emailObject.MailFrom is defaulted
    emailObject.BodyIsHtml = True
    emailObject.MailTo = "hello@world.com"
 
    'Send the email
    emailObject.SendMessage()
Catch ex As Exception
    Throw
End Try 

Simpler Synchronous Example:

Try
    'Get an Email object
    Dim emailObject As New Utilities.Email("FromAddress@world.com", "ToAddress@world.com", "Random Subject", "Email Body")
    emailObject.BodyIsHtml = True
   
    'Send the email
    emailObject.SendMessage()
Catch ex As Exception
    Throw
End Try

 

Download Source

 Email.zip (4kb Zip)

 


Posted Oct 07 2008, 03:49 PM by Jerald Carter
Filed under: ,

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
© Jerald Carter 1999 - 2008
Powered by Community Server (Non-Commercial Edition), by Telligent Systems