Sending emails using Asp.Net has never been as easier and manageable than with introduction of System.Net.Mail in ASP.Net 2.0. Though it always has been relatively easy to create a MailMessage and send it through SMTP, I have seen myself and lots of other developers struggle with decisions like if one should create the body for the message in code, put it in config file/database/ flat file. Depending on the project requirement and developer’s intuition, text could go anywhere. And time required to put something together were comparable.
One of my favorite choices is putting the template in a text file. Later, merging it with custom fields during runtime.
Ex: Template.txt
This code was generated at <%DATETIME%> from <%WEBSITE%>
Ex: Code Substitution
This code was generated at 12:45:00 PM from DOTNETLOG.com
This method decouples the message from code and is easier to manager, however, in .Net 1.1 this meant writing code to open file and also writing the substitution method. In 2.0, System.Web.UI.WebControls.MailDefinition object makes life a lot easier. Below is an example where I use MailDefinition and ListDictionary substitution collection to dynamically generate the mail message. This gives me flexibility, if I want to change the template later on.
using
System.Web.UI.WebControls;
using System.Mail.Net;
using System.Collections.Specialized;
//----------------------------------------------
//Create MailDefinition
MailDefinition md = new MailDefinition();
//specify the location of template
md.BodyFileName = @"c:\template.txt";//Build replacement collection to replace fields in template
ListDictionary replacements = new System.Collections.Specialized.ListDictionary();
replacements.Add("<%DATETIME%>", DateTime.Now.ToShortDateString());
replacements.Add("<%WEBSITE%>", "DOTNETLOG.com");//now create mail message using the mail definition object
// the CreateMailMessage object takes a source control object as the last parameter, if the object you are working with is webcontrol then you can just pass "this", otherwise create a dummy control as below.
MailMessage msg = md.CreateMailMessage(emailTo, replacements,
msg.Subject =
msg.From =
new System.Web.UI.WebControls.Panel());"Test Message";
msg.To = "test@dotnetlog.com";"admin@dotnetlog.com";//this uses SmtpClient in 2.0 to send email, this can be configured in web.config file. See example
SmtpClient smtp =
Ex: Web.Config
<
system.net>
<mailSettings>
<smtp deliveryMethod=" Network" from="admin@dotnetlog.com">
<network host=" mail.dotnetlog.com" port= "25" userName="test" password= "test"/>
</smtp>
</mailSettings>
</system.net>new SmtpClient();
smtp.Send(msg);