|
Who Are We?Fluent Consulting is a software development and consulting firm that specializes in enterprise application integration, web applications, and software product development. We are a dedicated team focused on providing the highest level of quality and value for our clients. Please feel free to visit our corporate site or get in touch! |
Creating Templated Emails
Often we need to generate email responses from our ASP.NET applications. Users forget their passwords, need email confirmations, or we'd just like to send them a friendly thank you for signing up.
Now you could create that email message with a nice series of string concatenations, or some fancy xml/xslt transformation. But who needs that when there is an easier way using what's available from our aspx parser?
First thing to create is a typical user control. This will be your template.
ForgotPasswordEmail.ascx<%@ Control Language="c#" AutoEventWireup="false" Codebehind="ForgotPasswordEmail.ascx.cs" Inherits="EmailTemplateExample.ForgotPasswordEmail" %> Here is your password reminder. ----------------------------------- YOUR ACCOUNT INFORMATION: Login: <%= Username %> Password: <%= Password %> ----------------------------------- TO CHANGE YOUR ACCOUNT INFORMATION: You can change your account information by logging in and selecting 'Account Information'. This is an automated message; please do not reply to this email.ForgotPasswordEmail.ascx.cs
namespace EmailTemplateExample { public abstract class ForgotPasswordEmail : System.Web.UI.UserControl { public string Username; public string Password; } }Once you have created the template, using it only takes a few lines of code.
using System; using System.IO; using System.Web.UI; using System.Web.Mail; ... //Load the user control ForgotPasswordEmail emailTemplate = (ForgotPasswordEmail)LoadControl("~/ForgotPasswordEmail.ascx"); emailTemplate.Username = "jroberts"; emailTemplate.Password = "a7e945"; //Render the user control to a string StringWriter stringWriter = new StringWriter(); HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter); emailTemplate.RenderControl(htmlWriter); string body = stringWriter.ToString(); //Send the email SmtpMail.SmtpServer = "localhost"; SmtpMail.Send("system@localhost","jroberts@localhost", "Password Reminder", body);Your template could have more complex behavior, having the full power of the ASP.NET user control model. Additionally, using html in your user control to create html emails only requires properly setting the format of the MailMessage.
//Prepare HTML email MailMessage mailMessage = new MailMessage(); mailMessage.From = "system@localhost"; mailMessage.Subject = "Password Reminder"; mailMessage.BodyFormat = MailFormat.Html; mailMessage.UrlContentBase = "http://localhost/"; //Send the email SmtpMail.SmtpServer = "localhost"; SmtpMail.Send(mailMessage);



