using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using DotNet.FrameWork.Common.Encrypt;
using HaTeam.Dd.Model;

namespace HteamDd.Web.Web.Dd_Eamil_active
{
    public partial class Dd_Email_send : System.Web.UI.Page
    {
        XmlDocument xmldocument = new XmlDocument();
        public string seandfrom = "", password = "", email;
        string strPath = GetWebSiteUrl.GetWebUrl;
        public bool istrue = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["PPOEEMAIL"] != null)
                {
                    email = Session["PPOEEMAIL"].ToString();//用户邮箱
                    updateXml();
                    ReadXml();
                }
                else
                {
                    email = "immaster@haitian.com.cn";//不清楚
                }
                string sendfrom = seandfrom;//发件人邮箱
                string senderaccount = "haitian";
                string pwd = password;
                string receiver = email;//用户注册时用的邮箱账号
                string subject = "你好";
                string pas = Session["Password"].ToString();//注册时的密码
                int iLenPas = pas.Length;
                pas = pas.Substring(0, 2);
                for (int i = 0; i < iLenPas - 2; i++)
                {
                    pas += "*";
                }

                string ip = Session["IP"].ToString();
                string name = Session["Name"].ToString();//博客名称
                DateTime time = Convert.ToDateTime(Session["Time"].ToString());
                string body = "<strong style=font-size:16px;" + ">尊敬的" + name + "</strong><br />欢迎加入海天大家庭!!!<br />您的登录账号为： " + receiver + "<br />密码为：" + pas + " ip地址为：" + ip + ",注册时间为：" + time + "<br /><font color=" + "red" + ">为保证您的账号能够正常使用，请点击链接，激活账号</font><br/><a title=\"激活登陆账号\" href=\"";
                string link = strPath + "/web/Dd_Eamil_active/Dd_reg_is_active.aspx?action=tdc%BDF%lhhy%ghdifs%dfgr&userguid=" + Session["userID"].ToString() + "&time=" + time;
                body = body + link + "\">" + strPath + Encrypt.EncryptPassword(link, "MD5") + Encrypt.EncryptPassword(link, "SHA1") + "</a>";
                string server = "smtp.163.com";
                try
                {
                    SendMail(sendfrom, senderaccount, pwd, receiver, subject, body, server);
                    istrue = true;
                }
                catch
                {
                    istrue = false;
                    SendMail("haitianxw001@163.com", senderaccount, "haitianxw1", receiver, subject, body, server);
                    Response.Write("<script language='javascript'>alert('对不起今日邮件发送已达上线，你可能无法收到激活链接！');window.location.href='/Dd_login.aspx'</script>");
                }
                if (istrue)
                {
                    Response.Redirect("/Web/Dd_Eamil_active/Dd_register_success.aspx");
                }                 
            }                      
        }

        /// <summary>
        /// 方法功能:发送邮件到指定联系人
        /// </summary>
        /// <param name="sendfrom">发送方的邮箱</param>
        /// <param name="senderaccount">发送方的名称</param>
        /// <param name="pwd">发送方的邮箱密码</param>
        /// <param name="receiver">接收方的邮箱</param>
        /// <param name="subject">邮件的主题</param>
        /// <param name="body">邮件的内容</param>
        /// <param name="mailserver">邮箱服务器</param>
        /// <returns>返回整数表示发送状态</returns>        
        public void SendMail(string sendfrom, string senderaccount, string pwd, string receiver, string subject, string body, string mailserver)
        {

            jmail.MessageClass MyMail = new jmail.MessageClass();
            string SendTo = receiver;　　//收件人
            string FromMail = sendfrom;//发件人
            string Title = subject; //邮件主题
            string Body = body;   //邮件主体
            string ShowName = "HTEMS";//显示名字
            //取email的@前面部分为用户名,即ustbwuyi1,当然也可以自己设置.
            string MailUserName = FromMail.Substring(0, FromMail.IndexOf("@"));
            string MailPassword = pwd;
            if (SendTo != "")
            {
                // 字符集
                MyMail.Charset = "GB2312";
                MyMail.ContentType = "text/html";
                //附件的编码格式
                MyMail.Encoding = "BASE64";
                ////是否将信头编码成iso-8859-1字符集
                MyMail.ISOEncodeHeaders = false;
                //发送人邮件地址
                MyMail.From = FromMail;
                //发送人姓名
                MyMail.FromName = ShowName;
                // 邮件主题
                MyMail.Subject = Title;
                //身份验证的用户名
                MyMail.MailServerUserName = MailUserName;
                //用户密码
                MyMail.MailServerPassWord = MailPassword;
                //邮件内容
                MyMail.Body = Body;
                try
                {

                    MyMail.AddRecipient(SendTo, "", "");
                    MyMail.Send(mailserver, false);
                }
                catch (Exception ex)
                {
                    Response.Write("<script language='javascript'>alert('邮件发送失败！');window.location.href='/Dd_login.aspx'</script>");
                }
            }

        }
        /// <summary>
        /// 每天自动修改XMLEmail.xml的初始值
        /// </summary>
        /// 
        public void updateXml()
        {
            xmldocument.Load(Server.MapPath("XMLEmail.xml"));
            XmlNodeList nodelist = xmldocument.SelectSingleNode("Emailstore").ChildNodes;
            foreach (XmlNode xn in nodelist)
            {
                XmlElement xe = (XmlElement)xn;
                if (xe.GetAttribute("Description") != DateTime.Now.Date.ToString())
                {
                    xe.SetAttribute("Description", DateTime.Now.Date.ToString());
                    XmlNodeList nodeschild = xe.ChildNodes;
                    foreach (XmlNode xn1 in nodeschild)
                    {
                        XmlElement xe1 = (XmlElement)xn1;
                        if (xe1.Name == "count")
                        {
                            xe1.InnerText = "0";
                        }
                        if (xe1.Name == "available")
                        {
                            xe1.InnerText = "true";
                        }
                    }
                }
            }
            xmldocument.Save(Server.MapPath("XMLEmail.xml"));
        }
        /// <summary>
        /// 获取XMLEmail.xml的文件值取出邮箱名和密码并赋值给全局变量
        /// </summary>
        public void ReadXml()
        {
            xmldocument.Load(Server.MapPath("XMLEmail.xml"));
            XmlNodeList nodelist = xmldocument.SelectSingleNode("Emailstore").ChildNodes;
            foreach (XmlNode xn in nodelist)
            {
                XmlElement xe = (XmlElement)xn;
                int count = int.Parse(xn["count"].InnerText);
                if (xn["available"].InnerText == "true" && count < 200)
                {
                    seandfrom = xe.GetAttribute("emailName");
                    password = xe.GetAttribute("password");
                    count += 1;
                    xn["count"].InnerText = count.ToString();
                    break;
                }
                else
                {
                    xn["available"].InnerText = "false";
                }
            }
            xmldocument.Save(Server.MapPath("XMLEmail.xml"));
        }
    }
}