A lot of the sites we build include email functionality … send-to-a-friend, invites, confirmation emails, admin error notices, etc. Here’s one way to do it.
First you need to have an HTML email. Rather than putting this in my code-behind I keep it as a separate file so if someone wants to update it later on they just have to deal with the HTML … and there are always changes. The HTML will include tokens for the instances where we want to insert items, like names, email addresses, hyperlinks, etc. Like so …
<p>Hello [FIRSTNAME],</p>
<p>Thank you for registering at [WEBSITENAME]!</p>
Then in our code-behind I create a StringBuilder object and read in the HTML file using a StreamReader. I use a StringBuilder over just a String because I can call helper methods like StringBuilder.Replace() and it works on the existing object. With String I would have to create a new instance to hold the results of the Replace(). So I do a replace for each time I want to replace a token in the HTML with some text. In this example I’m replacing [FIRSTNAME] with the email recipient’s first name and [WEBSITENAME] with the name of the website the user just registered at.
Dim oStrRdr As System.IO.StreamReader
Dim docPath as String = Server.MapPath("email.html")
Dim contents As New StringBuilder
If System.IO.File.Exists(docPath) Then
oStrRdr = System.IO.File.OpenText(docPath)
contents.Append(oStrRdr.ReadToEnd)
oStrRdr.Close()
End If
contents.Replace("[FIRSTNAME]", "Jason")
contents.Replace("[WEBSITENAME]", "ChetWeb.com")
Now I just need to send my email (assuming that the SMTP server we’re using is named in the web.config file in a key called “smtpserver”.
Dim mm As New System.Net.Mail.MailMessage("sender@somedomain.com","recipient@gmail.com","Welcome to my world!",contents.ToString)
mm.IsBodyHtml = True
mm.BodyEncoding = System.Text.Encoding.UTF8
Dim smtp As New System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings("smtpserver").ToString)
smtp.Send(mm)
One important setting that you need to make is “IsBodyHtml=True”. This tells the MailMessage object that the email is an HTML email. The other setting “BodyEncoding=’utf-8′” is especially important when you’re sending non-Latin based language emails, like Japanese. If you don’t specify the character encoding used for the body your recipient could receive gibberish.