Wednesday, September 28, 2011

Send email easily

Preface

Sending email in .Net it's not complicated thing . You can do it via config file or via code.
But we will create an email sender compoment that will encapsulate the process of sending email.
In future we will use this component in order to send a stock graph in program that we created

Implementation

Lets start our desing with the UML .




First we create base class  "SMTPBase". The class will implement IDisposable interface.
The interface will help to Garbage Collector to free resources that were allocated by this object.

The class will have a basic functionality to send emails. We will define properties such as :
  • From  - sender email
  • To  - recipient email 
  • Subject - email subject
  • SmtpHost  - smtp server host
  • Port - smtp port
  • Body - email text
  • Attachment - files that we want to attach to the email
 Of course we need to include validation if email valid or not. The most effective way  to do it
 is by regular expression.

Regex re = new Regex(@"\w.\w@{1,1}\w[.\w]?.\w");return re.IsMatch(email);

Email can be send using Gmail or Hotmail accout. We will define an Enum that will holds various account types and we will call it "SMTPHostType".


At the end we will create the service class that will send an email. Of course
the class will inherit from our base class. We will call it "SMTPSender".


The class will have several constructors


Constructor that receives host and port
public SMTPSender(string host, int port) : base(host, port) { }


Constuctor that will receive Host type Like Google or Hotmail
public SMTPSender(SMTPHostType smtpHost) : base(smtpHost ) { }




Here is a sample code that can be used in order to send an email.

using (SMTPSender smtpSender = new SMTPSender(SMTPHostType.HOTMAIL, "john@hotmail.com", "johnpass"))"john@gmail.com", "john@gmail.com", string.Empty, "Subject", "Text Body")

All the code can be dowloaded from here.

Summary

We created in this blog component that knows how to send emails using .Net .

No comments:

Post a Comment