Sending EMAIL from your Web Application

On my travels, one thing that I got asked a lot about is sending email from your web application. This is typically when you need to send a confirmation at the end of a transaction. I got a number of questions about how you do this without using Microsoft Exchange, etc, etc. While the full answer is here (including source code), below is some of the high level details.

The answer to the first problem is pretty simple. Using the .NET framework there is a class which handles the sending for you.

In C# you getting the following syntax, with Visual Basic below. They both use the System.Net.Mail namespace, plus you will probably need others such as System.Net.Mime to help with the encoding.

C# example

SmtpClient smtpClient = new SmtpClient();
MailMessage mail = new MailMessage();
mail.To.Add(newUserEmail);
mail.Subject = "Welcome to Sample App";
mail.IsBodyHtml = false;
mail.Body = string.Format(
    "Welcome {0} to Sample App!\nNow you can log in to the site!",
    newUserName);

smtpClient.Send(mail);

 

Visual Basic .NET example
Dim smtpClient As New SmtpClient()
Dim mail As New MailMessage()
mail.To.Add(newUserEmail)
mail.Subject = "Welcome to Sample App"
mail.IsBodyHtml = False
mail.Body = String.Format("Welcome {0} to Sample App!" & Constants.vbLf & "Now you can log in to the site!", newUserName)

smtpClient.Send(mail)

While this will create the email ( EML file ) and place it in a specific directory, you will probably need to format the message in a professional way, using some form of template based email. One option here is to use XSL to translate templates into specific mail messages, where you are taking a set of data represented as XML and rendering this into HTML using the XSLT. Below is a basic example.

 

XML
<?xml version="1.0" encoding="ISO-8859-1" ?>
<Properties>
  <UserName>frankm</UserName>
  <E-mail>frankm@contoso.com</E-mail>
</Properties>

When developing the XSLT templates, take into account the XML-serialized dictionary structure to retrieve the values using XPath in a value-of element. For instance, to retrieve the UserName value, use the following snippet in the XSLT template:

XSLT
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="https://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" indent="yes" />

  <xsl:template match="/">
    ...
    User Name: <xsl:value-of select="Properties/UserName"/>
    ...
  </xsl:template>
</xsl:stylesheet>

 

Rather than cutting a pasting lots of code, please go to the following example that I have placed on the web which contains all the source code and documentation to wire this up.