Saturday, April 18, 2009

Sending Formatted emails

There are more than one ways to achieve same goal. If you are required to send out email that looks like a fully formatted html page.
a simple approach will be to put the html code in string at codebehind appending the more html tags completing the layout.

something like :
Dim emailBody As StringBuilder = New StringBuilder
emailBody.Append("<tr><td style='font-size:10pt' align='right'><strong> EMail:</strong></td><td style='font-size:12pt' align='left'> " & txtEmail.Text & "</td></tr>")
emailBody.Append("<tr><td style='font-size:10pt' align='right'><strong> Comments:</strong></td><td style='font-size:12pt' align='left'> " & txtComments.Text & "</td></tr>")

sometime things might get messed up.
there is a major drawback in this approach you can't move to the design view in this aproach.

Another approach can be that if you design the template on aspx page design view the fill up the template with data and get the html code for that at runtime and send it in email.
for this you are required to use htmltextwriter.
following steps will do the job:
  1. Place your template in panel, keep its visiblity false.
  2. when email is required to be sent fill up the template with the required information.
  3. use the following code.

Dim stringWriter As New System.IO.StringWriter()

Dim htmlWriter As New System.Web.UI.HtmlTextWriter(stringWriter)

pnlTemplate.RenderControl(htmlWriter)

dim emailbodyhtml = stringWriter.ToString().Trim()

You will be using emailbodyhtml in the email something like

Dim msg As MailMessage = New MailMessage()

msg.Body = emailbodyhtml

msg.IsBodyHtml = True

Important: for some controls especially datacontrols you might get exception like

Control 'controlname' of type 'control type' must be placed inside a form tag with runat=server.

to solve this we are required to override the servercontrol verifictaion

Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)

Return

End Sub

hope this could be helpful.

No comments: