Almost all the projects have some requirement of sending emails out of the system. In this post, I will walk through a simple email wrapper class that I wrote and have used it successfully in several projects.
Step 1:
Add the following entry in your app.config or web.config file.
<system.net>
<mailSettings>
<smtp from=mailto:from=from@yourcorp.com>
<network host="mail.yourcorp.com"/>
</smtp>
</mailSettings>
</system.net>
Step 2:
Use the email.cs class provided in this post. If you are developing asp.net application, simply add this file to your app_code folder. One thing that you must ensure is that the Email class have access to SMTP settings which we created in step 1.
Step 3:
Now, only part remaining is to instantiate the email class object and call SendMail function. The following line should do the tricks for you.
Email oEmail = new Email();
oEmail.SendMail("YourEmail@YourCorp.com","To_1@YourCorp.com,To_2@YourCorp.com,To_3@YourCorp.com"," Some Subject", "Some Body");
If you have need to send CC and Bcc then there are few overloads to SendMail function available. Besides, all the mailobjects setting are declared as public, so you can also explicitly set To, CC, BCC, Subject, Body etc and simply call oEmail.SendMail(). The object requires To, From, Subject & Body filled in and rest of the settings are totally optional. In case if you are missing the required settings, the mailObject will error out and you will see an ArgumentException exception.
Why use a wrapper class:
There are several reasons to use a wrapper class as opposed to going directly against System.Net.Mail. Here are few that I am listing for your convenience.
A) You want more control over how the message is formatted in a consistent way.
B) You want ease of creating a mail message. Out of Box asp.net mail object doesn't support comma delimited To, CC and Bcc addresses. This class helps you get over that hurdle.
C) You can set and enforce standards by using wrapper classes. This stands true with any wrapper class that you want to create.
Conclusion:
This class has worked great and have met my requirements of sending emails from .net application. The real kicker is when a company has special security mandate that disallows sending emails from the front end web servers. In which case, I would recommend moving this class behind firewall and then using .net Remoting or Web Services to send emails. Let me know your thoughts.