How to Send Emails Using a Template in ASP.net
Written by David Bauernschmidt Tuesday, 5 March 2013
Over the years sending email in asp.net has gotten easier and easier but the requirements have gotten more complex. I want to show you how to using the system.net.mail reference to send emails using templates. I have a client that wants someone to fill out their information and have all that data placed into an email and sent to them. By taking advantage of email templates inside of asp.net this becomes a lot easier to manage. I could just create an html page and highlight everything between the body tags and use that to build a very large string and use that to replace text and to send it. There are a couple of problems with this choice.
1. You end up building one very long string by concatenating the entire html string.
2. If you wanted to change the template at all you would have to redeploy the libraries that built the html string.
3. If you have an error then you are left to try and debug something that is very long.
By implementing email templating in ASP.net you no longer have to deal with the issues above.
Just create an html page and save it as a .txt file somewhere on your site. With this mind you end up with something like this. This is your email template.
<b> <%FromName%><br /> <%FromCompany%> <br /> This is a test for Email Templating
Once this is done then create your email page that will call this. Like this
Dim EmailFrom As String = "[email protected]" Dim Emailto As String = "[email protected]" Dim subject As String = "Email Template Sample" Dim mail As New MailMessage(EmailFrom, Emailto) mail.Subject = subject mail.IsBodyHtml = True mail.Body = GetEmailBody() '// Replace placeholders in template. mail.Body = mail.Body.Replace("<%FromName%>", txtName.Text.ToString) mail.Body = mail.Body.Replace("<%FromCompany%>", txtCompany.Text.ToString) 'send the message Dim smtp As New SmtpClient() smtp.Send(mail) Response.Write("Message Sent")
NOTE: I have the email being sent locally. To understand this you can read this blog.
I have not provided all of the code just the specifics. However; if you want the details or you want to download the project then you can get it here.
-DOWNLOAD THE PROJECT-
Looking for quality web hosting? Look no further than Arvixe Web Hosting!