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>
ASP.NET读取配置文件发送邮件的更多相关文章
- asp.net 读取配置文件方法
方法1: System.Collections.Specialized.NameValueCollection nvc = (System.Collections.Specialized.NameVa ...
- Asp.NetCore 读取配置文件帮助类
/// <summary> /// 读取配置文件信息 /// </summary> public class ConfigExtensions { public static ...
- 【无私分享:ASP.NET CORE 项目实战(第八章)】读取配置文件(二) 读取自定义配置文件
目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 我们在 读取配置文件(一) appsettings.json 中介绍了,如何读取appsettings.json. 但随之产生 ...
- ASP.NET Core开发-读取配置文件Configuration
ASP.NET Core 是如何读取配置文件,今天我们来学习. ASP.NET Core的配置系统已经和之前版本的ASP.NET有所不同了,之前是依赖于System.Configuration和XML ...
- ASP.NET伪静态-无法读取配置文件,因为它超过了最大文件大小的解决办法
一直都在使用微软URLRewriter,具体的使用方法我就不多说了,网上文章很多. 但最近遇到一个问题,就是当web.config文件里面设置伪静态规则过多,大于2M的时候,就报错:无法读取配置文件, ...
- asp.net core轻松入门之MVC中Options读取配置文件
接上一篇中讲到利用Bind方法读取配置文件 ASP.NET Core轻松入门Bind读取配置文件到C#实例 那么在这篇文章中,我将在上一篇文章的基础上,利用Options方法读取配置文件 首先注册MV ...
- Asp.net Core中使用Redis 来保存Session, 读取配置文件
今天 无意看到Asp.net Core中使用Session ,首先要使用Session就必须添加Microsoft.AspNetCore.Session包,默认Session是只能存去字节,所以如果你 ...
- ASP.NET Core开发-读取配置文件Configuration appsettings.json
https://www.cnblogs.com/linezero/p/Configuration.html ASP.NET Core 是如何读取配置文件,今天我们来学习. ASP.NET Core的配 ...
- Asp.net Core 和类库读取配置文件信息
Asp.net Core 和类库读取配置文件信息 看干货请移步至.net core 读取配置文件公共类 首先开一个脑洞,Asp.net core 被使用这么长时间了,但是关于配置文件(json)的读取 ...
随机推荐
- Dom对象的方法应用一getElementById技巧、getElementsByName() IE,firefox兼容
在document对象中有以下三个方法,对于程序员来说,真可谓无人不知,无人不晓,他们分别是: 1.getElementById() 返回对拥有指定 id 的第一个对 ...
- 物联网操作系统HelloX V1.79发布公告
经过HelloX开发团队近半年的努力,在HelloX V1.78版本基础上,增加许多功能特性,并对V1.78版本的一些特性进行了进一步优化之后,正式形成HelloX V1.79测试版本.经相对充分的测 ...
- Python内置数据类型之Dictionary篇
1.查看函数XXX的doc string. Python的函数是有属性的,doc string便是函数的属性.所以查看函数XXX的属性的方法是模块名.XXX.__doc__ 2.模块的属性 每个模块都 ...
- SQLServer的最大连接数 超时时间已到 但是尚未从池中获取连接
很多做架构设计.程序开发.运维.技术管理的朋友可能或多或少有这样的困惑: SQLServer到底支持多少连接数的并发? SQLServer是否可以满足现有的应用吗? 现有的技术架构支持多少连接数的并发 ...
- myeclipse svn配置
在MyEclipse 9.0中安装SVN插件遇到一些问题,参考网上一些方法,最终解决.以下是个人认为比较简易的方法,供参考: 安装过程: (1)svn的插件版本site-1.8.14.zip(可根据自 ...
- linux log4j 使用
1.首先到Apache官网下载log4j.jar文件http://logging.apache.org/log4j/1.2/download.html 引用到eclipse项目里面 2.在src目录下 ...
- 平庸与卓越的差别 z
本文是清华大学陈吉宁校长于在 2015 年第一次研究生毕业典礼暨学位授予仪式上的讲话,原文标题:选择与坚持.演讲非常精彩,值得您细细阅读. 亲爱的同学们: 今天,共有 1318 名同学获得博士.硕士学 ...
- ajax连接池和XMLHttpRequest
连接池 我们公司在路由和交换机web界面和后端交互全部采用的是自己封装的ajax组件完成的,组件有点老了,代码风格和其中的某些用法现在看起来都有点不习惯.今天把这个组件的核心部分的ajax连接池记录下 ...
- dzzoffice的树型结构用户管理设计
在DzzOffice1.1的开发中,针对用户使用群体重新设计了,机构.部门.用户管理应用. 传统OA,企业相关程序,一般是设置机构-设置部门-设置职位-添加用户这样的步骤.每个步骤分为不同的管理界面. ...
- PDF数据提取------2.相关类介绍
1.简介 构造数据类型PdfString封装Rect类,PdfAnalyzer类中定义一些PDF解析方法. 2.PdfString类与Rect类 public class PdfString : IC ...