using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;
using MySql.Data.MySqlClient;
using System.Web.Configuration;

public partial class SendMail : System.Web.UI.Page
{
	protected string siteName = "";
	public string siteTitle = "";
	public string siteKeywords = "";
	public string siteDescribe = "";
	public string siteLogoAddr = "";
	public string urlRule = "";
	public string siteCopyRight = "";
	public string themeHtml4Nav = "";
	public string themeHtml4Copyright = "";
	public string ThemeCSS = "";
	
	///邮件配置参变量
	string setTitle="电子邮件";
	string setContent="欢迎给我们发送电子邮件，您提交的信息将直接发送到我们的邮箱!";
	string setButtonName="发送";
	bool setOpen=true;
	string Host="smtp.126.com";
	string Account="";
	string PWD="";
	string FromMail="XXX@126.com";
	string ToMail="XXX@qq.com";
	
	
	MysqlHelp mh = null;
	DataTable dt = null;
	DeepSoon deepsoon = null;
	string treeStr = "<ul id='main-menu' class='sm sm-blue'><li><a href='/'>首页</a></li>";
	
	///定义树节点的结构体
	struct ClassTreeNode{
		public string ID;
		public string Name;
		public string OutLinkHref;
		public int Level;
		public string isHidden;
	}
	
	///获取模板文件代码的函数
	public string getThemeHtml(string filePath){
		string themeHtmlStr = "";
		System.Text.Encoding code = System.Text.Encoding.GetEncoding("gb2312");
		System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(filePath),code);
		themeHtmlStr = reader.ReadToEnd();
		reader.Close();
		return themeHtmlStr;
	}
	///显示节点+孩子节点
		private void showNodes(ClassTreeNode node)
        {
			this.showNodesFunction(node);
			treeStr +=	"</ul>";
			themeHtml4Nav = themeHtml4Nav.Replace("{dp:siteNav}", treeStr);
			
		}
		///显示节点递归函数
		private void showNodesFunction(ClassTreeNode node)
        {			
			DataRow [] rows = dt.Select("fatherId = '"+node.ID+"'"); ///筛选node的孩子节点
			if(rows.Length > 0 && node.Level > 0){
				treeStr +=	"<ul>";
			}
			
			///根据不同的url规则，生成菜单链接地址
			string treeItemStr = "";
			
			foreach(DataRow dr in rows) ///循环孩子节点
            {
				ClassTreeNode childNd;
				childNd.ID = dr["id"].ToString();                    ///孩子节点ID
                childNd.Name = dr["name"].ToString();                ///孩子节点Name
				childNd.OutLinkHref = dr["outLinkHref"].ToString();  ///孩子节点外链OutLinkHref
				childNd.Level = node.Level+1;                        ///孩子节点Level
				childNd.isHidden = dr["isHidden"].ToString();        ///孩子节点隐藏状态isHidden
				///if(childNd.isHidden == "False"){
					if(childNd.OutLinkHref != "")
						treeStr += "<li><a href='"+childNd.OutLinkHref+"' target='_blank'>" + childNd.Name +"</a>";
					else{
						switch (urlRule)
						{
							case "endWithASPX":
								treeItemStr = "<li><a href='list-"+childNd.ID+"-0.aspx'>" + childNd.Name +"</a>";
								break;
							case "endWithHTML":
								treeItemStr = "<li><a href='list-"+childNd.ID+"-0.html'>" + childNd.Name +"</a>";
								break;
							case "noPostfix":
								treeItemStr = "<li><a href='list-"+childNd.ID+"-0'>" + childNd.Name +"</a>";;
								break;
							case "activeArgs":
								treeItemStr = "<li><a href='list.aspx?classID="+childNd.ID+"'>" + childNd.Name +"</a>";
								break;
							default:
								treeItemStr = "<li><a href='list-"+childNd.ID+"-0.aspx'>" + childNd.Name +"</a>";
								break;
						}///end switch
						treeStr += treeItemStr;
					}///end else
					this.showNodesFunction(childNd);   ///递归调用自身
					treeStr +=	"</li>";
				}///end if	
            ///}
			if(rows.Length > 0 && node.Level > 0)
					treeStr +=	"</ul>";
		}
		
	protected void Page_Load(object sender, EventArgs e)
	{
		///创建数据连接对象：
		mh = new MysqlHelp();
		
		///获取主题风格数据
		DataTable themeDt = new DataTable();
		themeDt = mh.GetDatabysql("Select * From Theme4DeepSoon");
		if(themeDt.Rows.Count > 0){
			///获取导航栏模板代码
			themeHtml4Nav = getThemeHtml("Theme/"+themeDt.Rows[0]["ThemeName"].ToString()+"/T_nav.html");
			///获取版权信息模板代码
			themeHtml4Copyright = getThemeHtml("Theme/"+themeDt.Rows[0]["ThemeName"].ToString()+"/T_copyright.html");
			///获取模板的样式表文件路径
			ThemeCSS = "Theme/"+themeDt.Rows[0]["ThemeName"].ToString()+"/style.css";
		}
		else {
			string insertSQLStr = "insert into Theme4DeepSoon(ThemeName) Values('Default')";
			mh.Runsql(insertSQLStr);
			themeHtml4Nav = getThemeHtml("./Theme/Default/T_nav.html");
			themeHtml4Copyright = getThemeHtml("./Theme/Default/T_copyright.html");
			ThemeCSS = "./Theme/Default/style.css";
		}
		
		///设置网站风格的css文件路径：
		HtmlLink cssLink = new HtmlLink();
		cssLink.Attributes.Add("type","text/css");
		cssLink.Attributes.Add("rel","stylesheet");
		cssLink.Href = ThemeCSS;
		this.Page.Header.Controls.Add(cssLink);
		
		///查询数据库
		dt=new DataTable();
		dt = mh.GetDatabysql("Select * From Preference4DeepSoon");
		if(dt.Rows.Count > 0){
			siteName = dt.Rows[0]["siteName"].ToString();
			siteTitle = dt.Rows[0]["siteTitle"].ToString();
			siteKeywords = dt.Rows[0]["siteKeywords"].ToString();
			siteDescribe = dt.Rows[0]["siteDescribe"].ToString();			
			siteLogoAddr = dt.Rows[0]["siteLogoAddr"].ToString();
			urlRule = dt.Rows[0]["urlRule"].ToString();
			siteCopyRight = dt.Rows[0]["siteCopyRight"].ToString();
		}
		else {
			string insertSQLStr = "insert into Preference4DeepSoon(siteName,siteTitle,siteKeywords,siteDescribe,siteMain,siteLogoAddr,htmlDir,uploadFileDir,siteCopyRight,WatermarkLogo,urlRule) Values ('"+siteName+"','"+siteTitle+"','"+siteKeywords+"','"+siteDescribe+"','www.DeepSoon.com','System_Img/logo.png','/Html/','/uploadFile/','"+siteTitle+" | 版权所有&bull;侵权必究','/System_Img/WatermarkLogo.png','endWithASPX')";
			mh.Runsql(insertSQLStr);
			siteName = "地平线";
			siteTitle = "地平线官网";
			siteKeywords = "地平线，asp.net,门户网，论坛，开源，社区";
			siteDescribe = "地平线门户网是用ASP.Net+MySQL技术开发的一个开源产品，利用该软件您可以轻易的订制自己的博客，新闻系统。";			
			siteLogoAddr = "System_Img/logo.png";
			urlRule = "endWithASPX";
			siteCopyRight = "地平线官网 | 版权所有&bull;侵权必究";
		}
		///导航栏基本信息替换：
		string sitePos = "<a href='/'><b>" + siteName + "</b></a> &gt; <b>" + Page.Header.Title+"</b>";
		themeHtml4Nav = themeHtml4Nav.Replace("{dp:siteLogoAddr}", siteLogoAddr).Replace("{dp:siteTitle}", siteTitle).Replace("{dp:sitePos}", sitePos);
		
		///读取配置表信息：
		DataTable settingDt=new DataTable();
		settingDt = mh.GetDatabysql("Select * From MailSetting4DeepSoon");
		if(settingDt.Rows.Count > 0){
			setTitle = settingDt.Rows[0]["setTitle"].ToString();
			setContent = settingDt.Rows[0]["setContent"].ToString();
			setButtonName = settingDt.Rows[0]["setButtonName"].ToString();
			setOpen = (bool)settingDt.Rows[0]["setOpen"];
			Host = settingDt.Rows[0]["Host"].ToString();
			Account = settingDt.Rows[0]["Account"].ToString();
			PWD = settingDt.Rows[0]["PWD"].ToString();
			FromMail = settingDt.Rows[0]["FromMail"].ToString();
			ToMail = settingDt.Rows[0]["ToMail"].ToString();
			
		}
		this.labelMailTitle.Text = setTitle;
		this.labelMailInfor.Text = setContent;
		this.btnSend.Text = setButtonName;
		
		///标题以及当前位置：
		Page.Title = setTitle+"</b> &gt; <b>正文</b>";
		
		Page.Title = (Page.Header.Title.Replace("</b> &gt; <b>正文</b>", "").Replace("</b> &gt; <b>列表</b>", "") +" &brvbar; "+siteTitle).Replace("首页 &brvbar;", "")+" - Powered by deepsoon";
		
		///修改网站头信息
		HtmlMeta metaKeywords = new HtmlMeta();
		metaKeywords.Name = "keywords";
		metaKeywords.Content = siteKeywords;
		
		HtmlMeta metaDescribe = new HtmlMeta();
		metaDescribe.Name = "description";
		metaDescribe.Content = siteDescribe;
		
		HtmlHead head = Page.Header;
		head.Controls.Add(metaKeywords);
		head.Controls.Add(metaDescribe);
		
		///底部版权信息替换：
		string siteOppInfor = "GMT+8."+DateTime.Now.ToString("yyyy-MM-dd")+" "+DateTime.Now.ToLongTimeString().ToString()+". Deepsoon Open Source Soft";
		deepsoon = new DeepSoon();
		themeHtml4Copyright = themeHtml4Copyright.Replace("{dp:siteSystemInfor}",deepsoon.getSystemInfor()).Replace("{dp:siteCopyRight}",siteCopyRight).Replace("{dp:siteOppInfor}",siteOppInfor);
				
		///获取导航栏数据
		mh = new MysqlHelp();
		dt = mh.GetDatabysql("Select * From Class4DeepSoon Where isHidden = False Order By Id");
		///显示ID=?的节点+孩子节点，并设定层级初值level
		ClassTreeNode nd;
        nd.ID = "0";            ///节点ID
        nd.Name = "门户网";     ///节点Name
		nd.OutLinkHref = "";    ///节点外链Outlink
		nd.Level = 0;           ///节点Level
		nd.isHidden = "False";    ///节点隐藏状态isHidden
		showNodes(nd);
		
		///导航栏和版权信息模块显示到网页：
		this.labelSiteNav.Text = themeHtml4Nav;
		this.labelSiteCopyright.Text = themeHtml4Copyright;
		
		this.btnSend.Attributes.Add("onClick", "hiddFieldContent.value = document.getElementById('contentBox').contentWindow.document.body.innerHTML;"); 
		
		
    }
	
    protected void btnSend_Click(object sender, EventArgs e)
    {
        string StrTo = ToMail;
        string title = this.txtTitle.Text.Replace("'", "").Replace("select", "").Replace("delete", "").Replace("update", "").Replace("insert", "");
		string content = this.hiddFieldContent.Value.Replace("'","’").Replace("\"","").Replace("\\","&gt;");
		if(title != "" && content != ""){
			bool s = sendmail(StrTo, title, content);
			if(s)
				this.labelInfor.Text = "<font color=green>您的邮件已经成功发送给我们。</font>";
			else 
				this.labelInfor.Text = "<font color=red>邮件发送失败！</font>";
		}
		else
			this.labelInfor.Text = "<font color=red>邮件主题和内容都不能为空！</font>";
    }
    public bool sendmail(string StrTo, string title, string content)
    {
        string HostName = Host;   //STMP服务器地址
        string StrAccount = Account;       //SMTP服务帐号
        string StrPwd = PWD;       //SMTP服务密码
        string StrFrom = FromMail;  //发送方邮件地址
        SmtpClient _smtpClient = new SmtpClient();
        _smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
        _smtpClient.Host = HostName; ;//指定SMTP服务器
        _smtpClient.Credentials = new System.Net.NetworkCredential(StrAccount, StrPwd);//用户名和密码
        MailMessage _mailMessage = new MailMessage(StrFrom, StrTo);
        _mailMessage.Subject = title;//主题
        _mailMessage.Body = content;//内容
        _mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//正文编码
        _mailMessage.IsBodyHtml = true;//设置为HTML格式
		
		///ZIP附件
		string attFilePath = ""+this.FilePath.Text;
		int pos = attFilePath.LastIndexOf(".");
		if(pos > 0){
			string endName = attFilePath.Substring(pos);
			if(endName == ".zip"){
				var attach = new Attachment(@attFilePath, "application/x-zip-compressed");
				_mailMessage.Attachments.Add(attach);
			}
		}
		
        _mailMessage.Priority = MailPriority.High;//优先级
        try
        {
            _smtpClient.Send(_mailMessage);
			return true;
        }
        catch
        {
			return false;
        }
    }
	
}
