生成HTML并将其作为电子邮件发送
本文关键字:电子邮件 HTML 生成 | 更新日期: 2023-09-27 18:13:08
我用c#编写了代码,该代码应该在XSL样式表的帮助下转换XML,生成一些HTML并将其保存在XML和XSL所在的本地位置,然后将HTML作为电子邮件发送。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mail;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
public class SendMail
{
static void Main(string[] args)
{
{
try{
//load the Xml doc
XPathDocument XPathDoc = new XPathDocument(@"C:'Test'svnlog.xml") ;
XslTransform XslTrans = new XslTransform() ;
//load the Xsl
XslTrans.Load(@"C:'Test'svnlog.xsl") ;
//create the output stream
XmlTextWriter Writer = new XmlTextWriter(@"C:'Test'CommitReport.html", null);
//do the actual transform of Xml
XslTrans.Transform(XPathDoc,null, Writer);
Writer.Close() ;
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
using (StreamReader reader = File.OpenText(@"C:'Test'CommitReport.html"))
{
MailMessage Mail = new MailMessage();
Mail.To = ("pqr@dna.com ");
Mail.From = new MailAddress("abc@bac.com");
Mail.Subject = ("Commit Error Report");
Mail.IsBodyHtml = true; //defines that your email is in Html form
Mail.BodyFormat = (@"C:'Test'CommitReport.html");
Mail.Body = reader.ReadToEnd();
}
//create instance of smtpclient
SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;
smtp.Send(mail);
}
}
private static void MailAddress(string p)
{
throw new NotImplementedException();
}
}
我不确定以下行是否在本地保存html:
XmlTextWriter Writer = new XmlTextWriter(@"C:'Test'CommitReport.html", null);
我也得到一个新的错误:"类型或名称空间名称'Mail'不存在于名称空间'系统。Web'(您是否缺少程序集参考?)
SmtpClient类是在System.Net.Mail
命名空间中定义的,而不是System.Web.Mail
。您的代码需要一些修改。例如,像Response.Write(ex.Message);
这样的东西在控制台应用程序中几乎没有意义。确保合理处置一次性资源也很重要。
所以试着改进一下你的代码:
using System;
using System.IO;
using System.Net.Mail;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
class Program
{
static void Main()
{
try
{
var xPathDoc = new XPathDocument(@"C:'Test'svnlog.xml");
var xslTrans = new XslCompiledTransform();
xslTrans.Load(@"C:'Test'svnlog.xsl");
using (var writer = XmlWriter.Create(@"C:'Test'CommitReport.html"))
{
xslTrans.Transform(xPathDoc, null, writer);
}
var mail = new MailMessage();
mail.To.Add(new MailAddress("pqr@dna.com"));
mail.From = new MailAddress("abc@bac.com");
mail.Subject = "Commit Error Report";
mail.IsBodyHtml = true;
mail.Body = File.ReadAllText(@"C:'Test'CommitReport.html");
using (var smtpClient = new SmtpClient("smtp.yourhost.com"))
{
smtpClient.EnableSsl = true;
smtpClient.Send(mail);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
还要确保