Friday, July 14, 2006

Send Mail - formatted using XML & XSL

Most of the applications which we develop needs to send mails. Mails can be sent from ASP.Net using the System.Web.Mail.MailMessage class. This has been stated in an earlier post. This is an enhancement for the earlier method. We might need to format the mail before sending it out to the recepients. Various methods can be adopted for this purpose. One of the methods is to take the contents of the mail from an XSL file which can be merged with a DataXML.

In this method, we can seperate the Data and Presentation layers so that it is easy to modify the static contents of the mail without recompiling the program. The following is the code sample for doing the same.


private void SendMail(string DataXML, string XSLFileName, string ToEMailAddress, string CCEMailAddress, string FromEMailAddress)
{
string XML = GetFormattedXml(DataXML, XSLFileName);
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(XML);
System.Web.Mail.MailMessage oMail = new System.Web.Mail.MailMessage();
oMail.To = ToEMailAddress;

if (CCEMailAddress.Trim() != "")
oMail.Cc = CCEMailAddress;
oMail.From = FromEMailAddress;

oMail.Subject = xDoc.SelectSingleNode("//subject").InnerText;
oMail.Body = xDoc.SelectSingleNode("//messagebody").InnerXml;
oMail.BodyEncoding = System.Text.Encoding.UTF8;
oMail.BodyFormat = System.Web.Mail.MailFormat.Html;
System.Web.Mail.SmtpMail.SmtpServer = MailServer;
System.Web.Mail.SmtpMail.Send(oMail);

xDoc = null;
}

private string GetFormattedXml(string XML, string XSLFileName)
{
System.Xml.Xsl.XslTransform xslt = new System.Xml.Xsl.XslTransform();
xslt.Load(XSLFileName);
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(XML);
xslt.Transform(xDoc, null, stringWriter);
return stringWriter.ToString();
}

private string GetFormattedXml(string XML, string XSLFileName, System.Xml.Xsl.XsltArgumentList Arg)
{
System.Xml.Xsl.XslTransform xslt = new System.Xml.Xsl.XslTransform();
xslt.Load(XSLFileName);
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(XML);
xslt.Transform(xDoc, Arg, StringWriter);
return stringWriter.ToString();
}


See Also
  1. Sending Mail from .Net application

2 Comments:

Anonymous Anonymous said...

Genial post and this post helped me alot in my college assignement. Gratefulness you on your information.

9:10 AM  
Anonymous Anonymous said...

Nice dispatch and this post helped me alot in my college assignement. Thank you seeking your information.

9:35 PM  

Post a Comment

<< Home