Re: automating email with links to records just submitted to an SQL DB using asp.net (vb)



Jim,

What I usually do for emailing is create an XML file and call it, say,
email.config (naming it with a .config extension prevents a user from
pulling it up through the website). In the XML file I define a
template for any emails I want to send. I use something like:

<?xml version="1.0" encoding="utf-8"?>
<email server="smtpserver">
<template Id="EmailMessage1">
<from><![CDATA[]]></from>
<cc><![CDATA[]]></cc>
<subject><![CDATA[]]></subject>
<message format="HTML"><![CDATA[
<html><body>Email Message text to [~USER_NAME~]</body></html>]]>
</message>
</template>
</email>

**Take note of the [~USER_NAME~] token in the body. You can create as
many of these nodes as you need, for each type of email you want to
send.

Then I have code like the following to send the actual email:
public class TemplateEmail {
public static void Send(string templatePath, string templateID, string
recipients, Hashtable tokens)
{
//** Load the email configuration template
XmlDocument template = new XmlDocument();
template.Load(templatePath);

//** Pull out the template
XPathNavigator nav = template.DocumentElement.CreateNavigator();
string smtpServer = nav.GetAttribute("SMTPServer", String.Empty);
MailMessage msg = new MailMessage();

//** Process the message elements
XmlNode emailNode =
template.DocumentElement.SelectSingleNode(string.Format("Template[@Id='{0}']",
templateID));

if (emailNode == null) throw new Exception("Invalid or missing email
template identifier");
nav = emailNode.CreateNavigator();
if (!nav.MoveToFirstChild()) throw new Exception("Invalid email
template - no properties defined");

string token = string.Empty;
while (true)
{
switch (nav.Name)
{
case "From":
msg.From = nav.Value;
break;
case "Cc":
msg.Cc = nav.Value;
break;
case "Bcc":
msg.Bcc = nav.Value;
break;
case "Subject":
//** Perform the subject token replacements
msg.Subject = ReplaceTokens(nav.Value, tokens);
break;
case "Body":
//** Perform the subject token replacements
msg.Body = ReplaceTokens(nav.Value, tokens);
break;
default:
break;
}

if (!nav.MoveToNext()) break;
}

//** Send the message
msg.To = recipients;
SmtpMail.SmtpServer = smtpServer;
SmtpMail.Send(msg);
}

private static string ReplaceTokens(string source, Hashtable tokens)
{
string result = source;
foreach (string key in tokens.Keys)
{
result = result.Replace(key, tokens[key].ToString());
}

return result;
}
}

And then the calling program passes in a hashtable that contains the
tokens to be replaced, along with the value to replace it with. A call
for this case would look like this:
Hashtable properties = new Hashtable();
properties.add("[~USER_NAME~]", "ggalehouse");
Email.Send(path_to_email.config_file, "EmailMessage1", properties);
//EmailMessage one is the ID attribute within the email.config file.

I hope this helps. I've used this on numerous projects with great
results.

Thanks,
Gary

.



Relevant Pages