Thursday, July 19, 2007

Send Web User Control as Email

I often have to setup an application to auto-send emails. I use a user control as the body of the email to save time formatting the HTML.

private string getSupervisorEmailContent()
    string content;
    // create and populate an instance of a ContentControl user control
    EmailSupervisor cc = (EmailSupervisor)this.LoadControl("EmailSupervisor.ascx");
    cc.EmployeeName = this.lblEmployeeName.Text;
    cc.SystemLink = "http://" + HttpContext.Current.Request.Url.Host + "/TechLadder";
    // render the output of the user control to a string, for use by the email message body
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    System.IO.StringWriter sw = new System.IO.StringWriter(sb);
    System.Web.UI.HtmlTextWriter htmltw = new System.Web.UI.HtmlTextWriter(sw);
    content = sb.ToString();
    return content;
private void SendSupervisorEmail(string email)
        MailAddress from = new MailAddress("");
        MailAddress to = new MailAddress(email);
        MailMessage Message = new MailMessage(from, to);
        Message.IsBodyHtml = true;
        Message.Subject = "System Engineering Technical Ladder";
        string superMsg = getSupervisorEmailContent();
        Message.Body = superMsg;
        SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["Andrew:MailServer"]);
    catch (Exception ex)
        throw ex;