using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web.Configuration;
using System.Net.Mail;
using System.Net;
using System.Threading;

namespace WebConvert
{
    /// <summary>
    /// 发送EMAIL的类
    /// </summary>
    public class SendEmail
    {
        private delegate void FinishSend(string arg);
        static private event FinishSend finishSend;
        static SmtpClient sender;
        /// <summary>
        /// EMail 发送方法
        /// </summary>
        /// <param name="title">邮件标题</param>
        /// <param name="body">邮件正文</param>
        public static void SendEmailTxt(string title,string body)
        {
            sender= new SmtpClient();
            sender.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            string[] hostinfo = WebConfigurationManager.AppSettings["MailHost"].Split(new char[] { ',' });
            sender.Host = hostinfo[0];
            sender.Port = int.Parse(hostinfo[1]);
            //sender.UseDefaultCredentials = true;
            sender.Credentials = new NetworkCredential(hostinfo[2], hostinfo[3]);
            
            MailMessage msg= new MailMessage();
            msg.BodyEncoding = System.Text.Encoding.UTF8;
            msg.SubjectEncoding = System.Text.Encoding.UTF8;
            msg.IsBodyHtml = false;
            msg.Subject = "关于" + title + "顾客的定餐邮件";
            msg.Body = body;
            msg.From = new MailAddress(hostinfo[4]);
            msg.To.Add(WebConfigurationManager.AppSettings["MailClient"]);
            finishSend+=new FinishSend(SendEmail_finishSend);
            try
            {
                Thread th= new Thread(new ParameterizedThreadStart(Send));
                th.IsBackground = true;
                th.Start(msg);
            }
            catch (Exception ex)
            {
                JScript.JsAlert(ex.Message);
            }
            
            
        }
        private static void Send(object arg)
        {
            MailMessage msg=(MailMessage)arg;
            sender.Send(msg);
            //SendEmail.finishSend("发送完成");
        }
        private static void SendEmail_finishSend(string arg)
        {
            JScript.JsAlert(arg);
        }
    }
}
