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.
[sourcecode language=”html”]
<b>
<%FromName%><br />
<%FromCompany%> <br />
This is a test for Email Templating
[/sourcecode]
Once this is done then create your email page that will call this. Like this
[sourcecode language=”vb”]
Dim EmailFrom As String = “TestEmailfrom@test.com”
Dim Emailto As String = “TestEmailto@test.com”
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”)
[/sourcecode]
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!