ASP.NET读取配置文件发送邮件
之前写过一篇文章C#使用SMTP发送邮件
后来做了改进,改成读取独立的配置文件,本文只记录读取配置文件的部分,发送部分见上面的链接。
读取配置文件C#代码:
using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; using System.Xml; using System.IO; //using log4net; //using log4net.Config; namespace EmailTest.Common { #region SMTPEmailSetting信息 /// <summary> /// SMTPEmailSetting信息 /// </summary> public class SMTPEmailSetting { /// <summary> /// 私有日志对象 /// </summary> //private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private EmailInfo _emailInfo; public EmailInfo EmailInfo { get { return _emailInfo; } set { _emailInfo = value; } } #region 模板中的方法 /// <summary> /// 将对象序列化为XML字符串 /// </summary> /// <returns></returns> public string ToXml() { StringWriter Output = new StringWriter(new StringBuilder()); string Ret = ""; try { XmlSerializer s = new XmlSerializer(this.GetType()); s.Serialize(Output, this); // To cut down on the size of the xml being sent to the database, we'll strip // out this extraneous xml. Ret = Output.ToString().Replace("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", ""); Ret = Ret.Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", ""); Ret = Ret.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "").Trim(); } catch (Exception ex) { //logger.Error("对象序列化失败!"); //logger.Error("异常描述:\t" + ex.Message); //logger.Error("异常方法:\t" + ex.TargetSite); //logger.Error("异常堆栈:\t" + ex.StackTrace); throw ex; } return Ret; } /// <summary> /// 将XML字符串中反序列化为对象 /// </summary> /// <param name="Xml">待反序列化的xml字符串</param> /// <returns></returns> public SMTPEmailSetting FromXml(string Xml) { StringReader stringReader = new StringReader(Xml); XmlTextReader xmlReader = new XmlTextReader(stringReader); SMTPEmailSetting obj; try { XmlSerializer ser = new XmlSerializer(this.GetType()); obj = (SMTPEmailSetting)ser.Deserialize(xmlReader); } catch (Exception ex) { //logger.Error("对象反序列化失败!"); //logger.Error("异常描述:\t" + ex.Message); //logger.Error("异常方法:\t" + ex.TargetSite); //logger.Error("异常堆栈:\t" + ex.StackTrace); throw ex; } xmlReader.Close(); stringReader.Close(); return obj; } /// <summary> /// 从xml文件中反序列化对象 /// </summary> /// <param name="xmlFileName">文件名</param> /// <returns>反序列化的对象,失败则返回null</returns> public SMTPEmailSetting fromXmlFile(string xmlFileName) { Stream reader = null; SMTPEmailSetting obj = new SMTPEmailSetting(); try { XmlSerializer serializer = new XmlSerializer(typeof(SMTPEmailSetting)); reader = new FileStream(xmlFileName, FileMode.Open, FileAccess.Read, FileShare.Read); obj = (SMTPEmailSetting)serializer.Deserialize(reader); reader.Close(); } catch (Exception ex) { //logger.Error("读取配置文件" + xmlFileName + "出现异常!"); //logger.Error("异常描述:\t" + ex.Message); //logger.Error("引发异常的方法:\t" + ex.TargetSite); //logger.Error("异常堆栈:\t" + ex.StackTrace); obj = null; } finally { if (reader != null) { reader.Close(); } } return obj; } /// <summary> /// 从xml文件中反序列化对象,文件名默认为:命名空间+类名.config /// </summary> /// <returns>反序列化的对象,失败则返回null</returns> public SMTPEmailSetting fromXmlFile() { string SettingsFileName = this.GetType().ToString() + ".config"; return fromXmlFile(SettingsFileName); } /// <summary> /// 将对象序列化到文件中 /// </summary> /// <param name="xmlFileName">文件名</param> /// <returns>布尔型。True:序列化成功;False:序列化失败</returns> public bool toXmlFile(string xmlFileName) { Boolean blResult = false; if (this != null) { Type typeOfObj = this.GetType(); //string SettingsFileName = typeOfObj.ToString() + ".config"; try { XmlSerializer serializer = new XmlSerializer(typeOfObj); TextWriter writer = new StreamWriter(xmlFileName); serializer.Serialize(writer, this); writer.Close(); blResult = true; } catch (Exception ex) { //logger.Error("保存配置文件" + xmlFileName + "出现异常!"); //logger.Error("异常描述:\t" + ex.Message); //logger.Error("引发异常的方法:\t" + ex.TargetSite); //logger.Error("异常堆栈:\t" + ex.StackTrace); } finally { } } return blResult; } /// <summary> /// 将对象序列化到文件中,文件名默认为:命名空间+类名.config /// </summary> /// <returns>布尔型。True:序列化成功;False:序列化失败</returns> public bool toXmlFile() { string SettingsFileName = this.GetType().ToString() + ".config"; return toXmlFile(SettingsFileName); } #endregion } #endregion #region 重复的节点对应声明类 /// <summary> /// SMTPEmailSetting节点 /// </summary> public class EmailInfo { private string _publicEmail; public string PublicEmail { get { return _publicEmail; } set { _publicEmail = value; } } private string _publicEmailPwd; public string PublicEmailPwd { get { return _publicEmailPwd; } set { _publicEmailPwd = value; } } private string _publicEmailSMTPURL; public string PublicEmailSMTPURL { get { return _publicEmailSMTPURL; } set { _publicEmailSMTPURL = value; } } private string _publicEmailTitle; public string PublicEmailTitle { get { return _publicEmailTitle; } set { _publicEmailTitle = value; } } private string _publicEmailContent; public string PublicEmailContent { get { return _publicEmailContent; } set { _publicEmailContent = value; } } } #endregion }
配置文件示例:
<?xml version="1.0" encoding="utf-8" ?> <SMTPEmailSetting> <EmailInfo> <PublicEmail>yourEmail@sina.com</PublicEmail> <PublicEmailPwd>yourPWD</PublicEmailPwd> <PublicEmailSMTPURL>smtp.sina.com</PublicEmailSMTPURL> <PublicEmailTitle>“{0}”</PublicEmailTitle> <PublicEmailContent>{0}</PublicEmailContent> </EmailInfo> </SMTPEmailSetting>
使用示例:
SMTPEmailSetting emailSetting = new SMTPEmailSetting().fromXmlFile(Server.MapPath("SMTPEmailSetting.config")); string returnStr = SMTPEmail.SendEmail(lblEmail.Text, new Hashtable(), string.Format(emailSetting.EmailInfo.PublicEmailTitle, txtTitle.Text.Trim()), string.Format(emailSetting.EmailInfo.PublicEmailContent, txtRemark.Text), emailSetting.EmailInfo.PublicEmail, emailSetting.EmailInfo.PublicEmailPwd, emailSetting.EmailInfo.PublicEmailSMTPURL);
其他思路,使用web.config的外部文件(避免修改导致程序重启session丢失),参见http://msdn.microsoft.com/zh-cn/library/ms228154(v=vs.100).aspx
示例:
<appSettings file="relative file name" > </appSettings>