栀子花开

追求完美

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

using System;
using System.Data;
using System.Configuration;
using System.Web;
using Obx.Core.BusinessObjects;
using Obx.Core.Security;
using System.Net.Mail;
using System.Text;
using System.Xml;
using System.IO;
using System.Collections.Specialized;
using System.Collections.Generic;
using Obx.Common.Messaging.EMail.POP3;
//using Obx.Common.Messaging.Exchange;
using System.Text.RegularExpressions;
using System.Net;
namespace EmailParseBusinessTask
{
    public class EmailParseBusinessTask : BusinessTask, ICustomTask, ISetTaskProperties
    {
        #region BusinessTask Members

        private string EmailAddress = String.Empty;
        private string Username = String.Empty;
        private string Password = String.Empty;
        private string EmailType=String.Empty;
        private string Host = String.Empty;
        private int Port = 25;
        private bool EnableSSL = false;
        private string DoMain = String.Empty;
        private BusinessObject Requests = Broker.Objects["Requests"];
        private BusinessObject emailBO = Broker.Objects["Email"];
        private BusinessObjectQuery query = new BusinessObjectQuery();
        public override void ProcessTask(BusinessObjectInstance caller)
        {
            //<data>
            //<EmailAddress></EmailAddress>
            //<Username></Username>
            //<Password></Password>
            //<EmailType>POP|Exchange</EmailType>
            //<Host></Host>
            //<Port></Port>
            //<EnableSSL></EnableSSL>
            //<DoMain></DoMain>
            //</data>
            if (caller == null || (caller != null && caller.Bo.ID == this.BusinessObjectID))
            {
                XmlDocument TaskXML = new XmlDocument();
                TaskXML.LoadXml(this.TaskData);
                EmailAddress = TaskXML.GetElementsByTagName("EmailAddress")[0].InnerText;
                Username = TaskXML.GetElementsByTagName("Username")[0].InnerText;
                Password = TaskXML.GetElementsByTagName("Password")[0].InnerText;
                EmailType = TaskXML.GetElementsByTagName("EmailType")[0].InnerText;
                Host = TaskXML.GetElementsByTagName("Host")[0].InnerText;
               
                List<emailMessage> mails = new List<emailMessage>();
                switch(EmailType)
                {
                    case"POP":
                        Port =int.Parse(TaskXML.GetElementsByTagName("Port")[0].InnerText);
                        EnableSSL = bool.Parse(TaskXML.GetElementsByTagName("EnableSSL")[0].InnerText);
                        mails = GetEmailsFromSMTPServer(Host, Username, Password, Port, EnableSSL);
                        break;
                    case"Exchange":
                        DoMain = TaskXML.GetElementsByTagName("DoMain")[0].InnerText;
                        mails = GetEmailsFromExchangeServer(Host, DoMain, Username, Password);
                        break;
                }
                foreach (emailMessage e in mails)
                {
                    if (e.subject.Contains("Request Number "))
                    {
                        query = new BusinessObjectQuery();
                        query.QueryRows.Add(new QueryLine("RequestID", "equal", e.subject.Substring(e.subject.IndexOf("Request Number ") + 15)));
                        DataTable result = Requests.SelectRecords(query);
                        if (result.Rows.Count > 0)
                        {
                            foreach (DataRow r in result.Rows)
                            {
                                ModifyRequest(e, r["__RowID__"].ToString());
                            }
                        }
                        else
                        {
                            CreateNewRequest(e);
                        }
                    }
                    else
                    {
                        CreateNewRequest(e);
                    }
                }

            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="email"></param>
        private void CreateNewRequest(emailMessage email)
        {
            BusinessObjectInstance newInstance = Requests.CreateInstance();
            newInstance.LoadSchema();
            newInstance["RequestFromEmail"] = email.from;
            newInstance["RequestName"] = email.subject;
            newInstance["RequestDescription"] = email.body;
            newInstance["CreatedBy"] = email.from;
            newInstance["CreatedDate"] = DateTime.Now;
            newInstance["LastUpdatedBy"] = email.from;
            newInstance["LastUpdate"] = DateTime.Now;
            newInstance["Status"] = "New";
            newInstance["InternalStatus"] = "New";
            try
            {
                query = new BusinessObjectQuery();
                query.QueryRows.Add(new QueryLine("Email", "equal", email.from));
                DataTable result = Broker.Objects["Contact"].SelectRecords(query);
                if (result.Rows.Count > 0)
                {
                    newInstance["Company"] = result.Rows[0]["Company"];
                    newInstance["FirstName"] = result.Rows[0]["FName"];
                    newInstance["LastName"] = result.Rows[0]["LName"];
                    newInstance["PhoneNumber"] = result.Rows[0]["BPhone"];
                    newInstance["SalesRep"] = result.Rows[0]["FSaleRep"];
                }
            }
            catch { }
            newInstance.CreateNew(true);
            switch (EmailType)
            {
                case "POP":
                    if (email.attachments != "" && email.attachments != " ")
                    {
                        byte[] byteFile = null;
                        byteFile = Convert.FromBase64String(email.attachments);
                        FileAttachment file = new FileAttachment(DateTime.Now, email.displayname, DateTime.Now, email.displayname, "", email.attachmentName, byteFile, Requests, newInstance.RecordID);
                        newInstance.SaveFileAttachment(file);
                    }
                    break;
                case "Exchange":
                    if (email.attachmentByte != null)
                    {
                        FileAttachment file = new FileAttachment(DateTime.Now, email.displayname, DateTime.Now, email.displayname,"", email.attachmentName,email.attachmentByte,Requests, newInstance.RecordID);
                        newInstance.SaveFileAttachment(file);
                    }
                    break;
            }
        }

        private void ModifyRequest(emailMessage email, string RecordID)
        {
            BusinessObjectInstance instance = Requests.CreateInstance(RecordID.Replace('[', '\x01').Replace(']', '\x02'), true);
            instance.ForEdit = true;
            instance["LastUpdatedBy"] = email.from;
            instance["LastUpdate"] = DateTime.Now;
            instance.SaveRecord(false);
            instance.ForEdit = false;
            BusinessObjectInstance emailInstance = Requests.Children["Email"].CreateInstance();
            emailInstance.LoadSchema();
            emailInstance["ESubject"] = email.subject;
            emailInstance["EBody"]=email.body;
            emailInstance["EFrom"]=email.from;
            emailInstance["ETo"]=email.to;
            emailInstance["ERSTime"]=email.date;
            emailInstance.CreateNew(false);

            BusinessObjectRelation relation=Requests.ChildrenRelationship[Requests,Requests.Children["Email"]];
            relation.InsertMapInfo(instance, emailInstance);
        }


        /// <summary>
        ///
        /// </summary>
        /// <param name="server"></param>
        /// <param name="domain"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private List<emailMessage> GetEmailsFromExchangeServer(string server, string domain, string username, string password)
        {
            List<emailMessage> ReturnList = new List<emailMessage>();
            try
            {
                ExUser ExchangeUser = new ExUser(server, username, password, domain);
                ExInBox Inbox = new ExInBox(ExchangeUser);
                ExMailMessage[] message = Inbox.GetMessageListFromInbox();
                if (message.Length > 0)
                {
                    for (int i = 0; i < message.Length; i++)
                    {
                        emailMessage tmp = new emailMessage();
                        tmp.mailindex = i+1;
                        tmp.subject = message[i].Subject;
                        tmp.date = message[i].Date;
                        tmp.body = message[i].Body;
                        //tmp.attachments=message[0].Url
                        string from = message[i].From;
                        if(from.Contains("<"))
                            from = from.Substring(from.IndexOf('<') + 1, from.IndexOf('>') - 1 - from.IndexOf('<'));
                        tmp.from = from;
                        tmp.displayname = from;
                        string to = message[i].To;
                        if (to.Contains("<"))
                            to = to.Substring(to.IndexOf('<') + 1, to.IndexOf('>') - 1 - to.IndexOf('<'));
                        tmp.to = to;
                        tmp.displaytoname = to;
                        if (message[i].HasAttachment)
                        {
                            try
                            {
                                Attachment attach = GetAttachment(message[i], domain, username, password);
                                if (attach != null)
                                {
                                    tmp.attachmentByte = attach.attachmentByte;
                                    tmp.attachmentName = attach.attachmentName;
                                }
                            }
                            catch(Exception ex)
                            { }
                        }
                        ReturnList.Add(tmp);
                        Inbox.DeleteMessage(message[i].Url);
                    }
                }
            }
            catch(Exception e)
            {}
            return ReturnList;
        }
        #region
        private Attachment GetAttachment(ExMailMessage mailMessage, string domain, string username, string password)
        {
            // Variables.
            Attachment result = null;
            System.Net.HttpWebRequest Request;
            System.Net.WebResponse Response;
            System.Net.CredentialCache MyCredentialCache;
            System.IO.Stream ResponseStream = null;
            System.Xml.XmlDocument ResponseXmlDoc = null;
            System.Xml.XmlNode root = null;
            System.Xml.XmlNamespaceManager nsmgr = null;
            System.Xml.XmlNodeList PropstatNodes = null;
            System.Xml.XmlNodeList HrefNodes = null;
            System.Xml.XmlNode StatusNode = null;
            System.Xml.XmlNode PropNode = null;

            string[] _attachmentName = null;
            string[] _realAttachmentName = null;
            System.Xml.XmlNode NameNode = null;
            try
            {
                // Create a new CredentialCache object and fill it with the network
                // credentials required to access the server.
                MyCredentialCache = new System.Net.CredentialCache();
                MyCredentialCache.Add(new System.Uri(mailMessage.Url),
                    "NTLM",
                    new System.Net.NetworkCredential(username, password, domain)
                    );

                // Create the HttpWebRequest object.
                Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(mailMessage.Url);

                // Add the network credentials to the request.
                Request.Credentials = MyCredentialCache;

                // Specify the method.
                Request.Method = "X-MS-ENUMATTS";

                // Send the X-MS-ENUMATTS method request and get the
                // response from the server.
                Response = (HttpWebResponse)Request.GetResponse();

                // Get the XML response stream.
                ResponseStream = Response.GetResponseStream();

                // Create the XmlDocument object from the XML response stream.
                ResponseXmlDoc = new System.Xml.XmlDocument();

                // Load the XML response stream.
                ResponseXmlDoc.Load(ResponseStream);

                // Get the root node.
                root = ResponseXmlDoc.DocumentElement;

                // Create a new XmlNamespaceManager.
                nsmgr = new System.Xml.XmlNamespaceManager(ResponseXmlDoc.NameTable);

                // Add the DAV: namespace, which is typically assigned the a: prefix
                // in the XML response body.  The namespaceses and their associated
                // prefixes are listed in the attributes of the DAV:multistatus node
                // of the XML response.
                nsmgr.AddNamespace("a", "DAV:");

                // Add the http://schemas.microsoft.com/mapi/proptag/ namespace, which
                // is typically assigned the d: prefix in the XML response body.
                nsmgr.AddNamespace("d", "http://schemas.microsoft.com/mapi/proptag/");
                nsmgr.AddNamespace("e", "urn:schemas:httpmail:");
                // Use an XPath query to build a list of the DAV:propstat XML nodes,
                // corresponding to the returned status and properties of
                // the file attachment(s).
                PropstatNodes = root.SelectNodes("//a:propstat", nsmgr);

                // Use an XPath query to build a list of the DAV:href nodes,
                // corresponding to the URIs of the attachement(s) on the message.
                // For each DAV:href node in the XML response, there is an
                // associated DAV:propstat node.
                HrefNodes = root.SelectNodes("//a:href", nsmgr);

                // Attachments found?
                if (HrefNodes.Count > 0)
                {
                    _attachmentName = new string[HrefNodes.Count];
                    _realAttachmentName = new string[HrefNodes.Count];
                    // Display the number of attachments on the message.
                    // Iterate through the attachment properties.
                    for (int i = 0; i < HrefNodes.Count; i++)
                    {
                        // Use an XPath query to get the DAV:status node from the DAV:propstat node.
                        StatusNode = PropstatNodes[i].SelectSingleNode("a:status", nsmgr);

                        // Check the status of the attachment properties.
                        if (StatusNode.InnerText != "HTTP/1.1 200 OK")
                        {
                            return null;
                        }
                        else
                        {
                            // Get the CdoPR_ATTACH_FILENAME_W MAPI property tag,
                            // corresponding to the attachment file name.  The
                            // http://schemas.microsoft.com/mapi/proptag/ namespace is typically
                            // assigned the d: prefix in the XML response body.
                            NameNode = PropstatNodes[i].SelectSingleNode("a:prop/d:x3704001f", nsmgr);
                            // Get the CdoPR_ATTACH_SIZE MAPI property tag,
                            // corresponding to the attachment file size.
                            PropNode = PropstatNodes[i].SelectSingleNode("a:prop/d:x0e200003", nsmgr);
                            string size;
                            if (Convert.ToInt32(PropNode.InnerText) > 1024 * 1224)
                            {
                                size = (Convert.ToInt32(PropNode.InnerText) / (1024 * 1024)).ToString() + "M";
                            }
                            else if (Convert.ToInt32(PropNode.InnerText) > 1024)
                            {
                                size = (Convert.ToInt32(PropNode.InnerText) / 1024).ToString() + "KB";
                            }
                            else
                            {
                                size = PropNode.InnerText + "B";
                            }
                            int index = HrefNodes[i].InnerText.LastIndexOf('/') + 1;
                            string attachmentName = HrefNodes[i].InnerText.Substring(index);
                            int mLastIndex = attachmentName.LastIndexOf('.');
                            string mMainName = attachmentName.Substring(0, mLastIndex);
                            //mMainName = Server.UrlDecode(mMainName);
                            int mExtLength = attachmentName.Length - mLastIndex;
                            string mExtName = attachmentName.Substring(mLastIndex, mExtLength);
                            string LAttachment= mailMessage.Url + "/" + mMainName +  mExtName ;
                            _attachmentName[i] = mailMessage.Url + "/" + mMainName + mExtName + "/C58EA28C-18C0-4a97-9AF2-036E93DDAFB3/" + mMainName + mExtName + "?attach=1";
                            _realAttachmentName[i] = PropstatNodes[i].SelectSingleNode("a:prop/e:attachmentfilename", nsmgr).InnerText;
                        }
                    }

                }

                // Clean up.
                ResponseStream.Close();
                Response.Close();
                result = this.GetAttachmentFile(mailMessage, domain, username, password, HrefNodes.Count, _attachmentName,_realAttachmentName);
            }
            catch (Exception ex)
            {
                // Catch any exceptions. Any error codes from the X-MS-ENUMATTS
                // method request on the server will be caught here, also.

            }
            return result;
        }
        private Attachment GetAttachmentFile(ExMailMessage mailMessage, string domain, string username, string password, int Count, string[] _attachmentName, string[] _realAttachmentName)
        {
            //_attachmentName[0] = "http://mail.blifax.com/Exchange/HongC/Inbox/blifax.com.EML/1_multipart_xF8FF_3_1.0.0.15.sql";
            Attachment attach = new Attachment();
            System.Net.HttpWebRequest Request;
            System.Net.WebResponse Response;
            System.Net.CredentialCache MyCredentialCache;
            Stream ResponseStream = null;
            try
            {
                for(int i=0;i<_attachmentName.Length;i++)
                {
                    // Create a new CredentialCache object and fill it with the network
                    // credentials required to access the server.
                    MyCredentialCache = new System.Net.CredentialCache();
                    MyCredentialCache.Add(new System.Uri(_attachmentName[i]),
                        "NTLM",
                        new System.Net.NetworkCredential(username, password, domain)
                        );

                    // Create the HttpWebRequest object.
                    Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(_attachmentName[i]);
                    Request.UnsafeAuthenticatedConnectionSharing = true;
                    // Add the network credentials to the request.
                    Request.Credentials = MyCredentialCache;

                    // Specify the method.
                    Request.Method = "GET";

                    // Send the X-MS-ENUMATTS method request and get the
                    // response from the server.
                    Response = (HttpWebResponse)Request.GetResponse();
                   
                    // Get the XML response stream.
                    ResponseStream = Response.GetResponseStream();

                    MemoryStream ms = new MemoryStream();
                    StreamReader sr = new StreamReader(ResponseStream);
                    byte[] buffer = new byte[256];
                    int count = ResponseStream.Read(buffer, 0, 256);
                    while (count > 0)
                    {
                        ms.Write(buffer, 0, count);
                        count = ResponseStream.Read(buffer, 0, 256);
                    }
                    byte[] bs = ms.ToArray();
                    attach.attachmentByte = bs;
                    attach.attachmentName = _realAttachmentName[i];
                    ResponseStream.Close();
                    Response.Close();
                }
                return attach;
            }
            catch(Exception e)
            {
                return attach;
            }
        }
        #endregion
        /// <summary>
        ///
        /// </summary>
        /// <param name="server"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="port"></param>
        /// <param name="ssl"></param>
        /// <returns></returns>
        private List<emailMessage> GetEmailsFromSMTPServer(string server, string username, string password, int port, bool ssl)
        {
            Obx.Common.Messaging.EMail.POP3.Pop3MailClient pop = new Pop3MailClient(server, port, ssl, username, password);
            List<emailMessage> messages = new List<emailMessage>();
            try
            {
                Regex date = new Regex(@"(?:Date:(?<date>.+))");
                Regex from = new Regex(@"(?:From:(?<from>.+))");
                Regex to = new Regex(@"(?:To:(?<to>.+))");
                Regex subject = new Regex(@"(?:Subject:(?<subject>.+))");
                Regex dateRegex = new Regex(@"\w+,(?<date>[^\+\-]+)[\+\-].+");
                Regex matchSubject = new Regex(@"\#+(?<name>[^\#]+)\#+(?<id>[^\#]+)\#\#+");
                string message = "";


                pop.Connect();
                pop.IsAutoReconnect = true;
                pop.ReadTimeout =180000;
                int NumberOfMails, MailboxSize;
                pop.GetMailboxStats(out NumberOfMails, out MailboxSize);

                if (NumberOfMails > 0)
                {
                    for (int i = 1; i <= NumberOfMails; i++)
                    {
                        emailMessage m = new emailMessage();
                        pop.GetRawEmail(i, out message);

                        m.mailindex = i;
                        m.subject = subject.Match(message).Groups[1].Value;
                        try
                        {
                            m.date = Convert.ToDateTime(dateRegex.Match(date.Match(message).Groups[1].Value).Groups[1].Value);
                        }
                        catch
                        {
                            m.date = DateTime.Now;
                        }
                        m.body = GetEmailBody(message);
                        try
                        {
                            m.attachments = GetEmailAttachments(message, out m.attachmentName);
                        }
                        catch
                        { }
                        parsFrom(from.Match(message).Groups[1].Value, out m.displayname, out m.from);
                        parsTo(to.Match(message).Groups[1].Value, out m.displaytoname, out m.to);
                        messages.Add(m);
                    }
                    pop.DeleteEmail(1);
                }
                pop.Disconnect();
                return messages;
            }
            catch (Exception err)
            {
                pop.Disconnect();
                return messages;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private string GetEmailBody(string message)
        {
            string body = "";
            string code = "";
            string codeType = "7bit";
            try
            {
                body = message.Substring(message.IndexOf("Content-Transfer-Encoding:"));
                code = body.Substring(0, body.IndexOf("\r\n"));

                if (code.IndexOf("base64") >= 0)
                    codeType = "base64";
                body = body.Substring(body.IndexOf("\r\n\r\n") + 4);
                //if (body.IndexOf("\r\n\r\n--") > 0)
                //    body = body.Substring(0, body.IndexOf("\r\n\r\n--"));
                //else if (body.LastIndexOf("\r\n.\r\n") > 0)
                //    body = body.Substring(0, body.LastIndexOf("\r\n.\r\n"));
                if (body.IndexOf("\r\n--") > 0)
                    body = body.Substring(0, body.IndexOf("\r\n--"));
                else if (body.LastIndexOf("\r\n.") > 0)
                    body = body.Substring(0, body.LastIndexOf("\r\n."));

                body = body.Replace("Content-Disposition: inline\r\n", "");
                if (codeType == "base64" || message.IndexOf("charset=\"GB2312\"") > 0)
                {
                    return decodemail(body.Trim(), "gb2312");
                }
                else
                    return body;
            }
            catch (Exception err)
            {
                return "";
            }
            return message;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private string GetEmailAttachments(string message,out string name)
        {
            string body = "";
            string code = "";
            string codeType = "7bit";
            string fileName = "";
            try
            {
                //string str = message.Substring(message.IndexOf("Content-Type: text/plain; name="));
                string str = message.Substring(message.IndexOf("Content-Type: text/plain;"));
                if (str.Substring(str.IndexOf("Content-Transfer-Encoding:")).IndexOf("base64") >= 0)
                {
                    codeType = "base64";
                }
                body = message.Substring(message.IndexOf("Content-Disposition: attachment;"));
                fileName = message.Substring(message.IndexOf("Content-Disposition: attachment;"));
                fileName = fileName.Substring(fileName.IndexOf('=')+1, fileName.IndexOf("\r\n\r\n")-fileName.IndexOf('=')-1);
                fileName = fileName.Replace("\"", "");
                name = fileName;
                code = body.Substring(0, body.IndexOf("\r\n"));
                if (code.IndexOf("base64") >= 0)
                    codeType = "base64";
                body = body.Substring(body.IndexOf("\r\n\r\n") + 4);
                //if (body.IndexOf("\r\n\r\n--") > 0)
                //    body = body.Substring(0, body.IndexOf("\r\n\r\n--"));
                //else if (body.LastIndexOf("\r\n.\r\n") > 0)
                //    body = body.Substring(0, body.LastIndexOf("\r\n.\r\n"));
                if (body.IndexOf("\r\n--") > 0)
                    body = body.Substring(0, body.IndexOf("\r\n--"));
                else if (body.LastIndexOf("\r\n.") > 0)
                    body = body.Substring(0, body.LastIndexOf("\r\n."));
                body = body.Replace(code, "");
                if (codeType == "base64" || message.IndexOf("charset=\"GB2312\"") > 0)
                {
                    //return decodemail(body.Trim(), "gb2312");
                    return body.Trim();
                }
                else
                    return body;
            }
            catch (Exception err)
            {
                name = fileName;
                return " ";
            }
            return message;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="from"></param>
        /// <param name="displayname"></param>
        /// <param name="email"></param>
        private void parsFrom(string from, out string displayname, out string email)
        {
            Regex r = new Regex(@"(?<name>[^""\<]+)[^\<]*\<(?<from>[^\>]+)\>");
            Match m = r.Match(from);
            if (r.IsMatch(from))
            {
                displayname = m.Groups["name"].Value;
                email = m.Groups["from"].Value;
            }
            else
            {
                if (from != "")
                {
                    displayname = "";
                    email = from;
                }
                else
                {
                    displayname = "";
                    email = "";
                }
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="to"></param>
        /// <param name="displayname"></param>
        /// <param name="email"></param>
        private void parsTo(string to, out string displayname, out string email)
        {
            Regex r = new Regex(@"(?<name>[^""\<]+)[^\<]*\<(?<to>[^\>]+)\>");
            Match m = r.Match(to);
            if (r.IsMatch(to))
            {
                displayname = m.Groups["name"].Value;
                email = m.Groups["to"].Value;
            }
            else
            {
                if (to != "")
                {
                    email = to;
                    displayname = "";
                }
                else
                {
                    displayname = "";
                    email = "";
                }
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="body"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        private string decodemail(string body, string encode)
        {
            string s = body;
            try
            {
                if (encode != "")
                {
                    byte[] bytes = Convert.FromBase64String(body.Trim());
                    s = System.Text.Encoding.GetEncoding(encode).GetString(bytes);
                }
            }
            catch { }
            return s;
        }
        private string decodemail(byte[] bytes, string encode)
        {
            string s ="";//= body;
            try
            {
                if (encode != "")
                {
                    //byte[] bytes = Convert.FromBase64String(body.Trim());
                    s = System.Text.Encoding.GetEncoding(encode).GetString(bytes);
                }
            }
            catch { }
            return s;
        }
        #endregion

        #region ICustomTask Members

        private NameValueCollection viewState = new NameValueCollection();
        private string emailType = "POP";
        public string _winID=String.Empty;
        public string GetWindowContent(string winID)
        {
            this._winID = winID;
            StringBuilder winHtml = new StringBuilder();
            winHtml.Append("<div style=\"width:98%;  border: solid 1px #cccccc; position:relative; background-color: #FCFCFC;overflow:hidden; \">");

            winHtml.Append("<table width=\"100%\" border=\"0\" cellspacing=\"5\" cellpadding=\"0\">");

            winHtml.Append("  <tr>");
            winHtml.Append("    <td class=\"header_right_bold\">Email Address:</td>");
            winHtml.Append("    <td class=\"header_left\"><input type=\"text\" id=\"_EmailAddress\" value=\"" + this.viewState["_EmailAddress"] + "\" /></td>");
            winHtml.Append("  </tr>");

            winHtml.Append("  <tr>");
            winHtml.Append("    <td class=\"header_right_bold\">Username:</td>");
            winHtml.Append("    <td class=\"header_left\"><input type=\"text\"  id=\"_Username\" value=\"" + this.viewState[ "_Username"] + "\" /></td>");
            winHtml.Append("  </tr>");

            winHtml.Append("  <tr>");
            winHtml.Append("    <td class=\"header_right_bold\">Password:</td>");
            winHtml.Append("    <td class=\"header_left\"><input type=\"password\" id=\"_Password\" value=\"" + this.viewState["_Password"] + "\" /></td>");
            winHtml.Append("  </tr>");

            winHtml.Append("  <tr>");
            winHtml.Append("    <td class=\"header_right_bold\">Type:</td>");
            winHtml.Append("    <td class=\"header_left\">");
            winHtml.Append("      <select id=\"_Type\" name=\"_Type\" onchange=\"javascript:_AsycPostback('" + this._winID + "','ChooseServerType');\" >");
            winHtml.Append("          <option value=\"POP\" " + (this.viewState["_Type"] == "POP" ? "selected" : "") + ">POP</option>");
            winHtml.Append("          <option value=\"Exchange\" " + (this.viewState["_Type"] == "Exchange" ? "selected" : "") + ">Exchange</option>");
            winHtml.Append("      </select>");
            winHtml.Append("    </td>");
            winHtml.Append("  </tr>");

            winHtml.Append("  <tr>");
            winHtml.Append("    <td class=\"header_right_bold\">Host:</td>");
            winHtml.Append("    <td class=\"header_left\"><input type=\"text\"  id=\"_Host\" value=\"" + this.viewState["_Host"] + "\" /></td>");
            winHtml.Append("  </tr>");
            if (emailType == "POP")
            {
                winHtml.Append("  <tr>");
                winHtml.Append("    <td class=\"header_right_bold\">Port:</td>");
                winHtml.Append("    <td class=\"header_left\"><input type=\"text\"  id=\"_Port\" value=\"" + this.viewState[ "_Port"] + "\" /></td>");
                winHtml.Append("  </tr>");

                winHtml.Append("  <tr>");
                winHtml.Append("    <td class=\"header_right_bold\">EnableSSL:</td>");
                winHtml.Append("    <td class=\"header_left\">");
                winHtml.Append("      <select id=\"_EnableSSL\" name=\"_EnableSSL\" >");
                winHtml.Append("          <option value=\"True\" " + (this.viewState["_EnableSSL"] == "True" ? "selected" : "") + ">True</option>");
                winHtml.Append("          <option value=\"False\" " + (this.viewState["_EnableSSL"] == "False" ? "selected" : "") + ">False</option>");
                winHtml.Append("      </select>");
                winHtml.Append("    </td>");
                winHtml.Append("  </tr>");
            }
            else if (emailType == "Exchange")
            {
                winHtml.Append("  <tr>");
                winHtml.Append("    <td class=\"header_right_bold\">DoMain:</td>");
                winHtml.Append("    <td class=\"header_left\"><input type=\"text\"  id=\"_DoMain\" value=\"" + this.viewState[ "_DoMain"] + "\" /></td>");
                winHtml.Append("  </tr>");
            }
            winHtml.Append("</table>");

            winHtml.Append("</div>");

            return winHtml.ToString();
        }

        public System.Xml.XmlDocument GetXML()
        {
            //<data>
            //<EmailAddress></EmailAddress>
            //<Username></Username>
            //<Password></Password>
            //<EmailType>POP|Exchange</EmailType>
            //<Host></Host>
            //<Port></Port>
            //<EnableSSL></EnableSSL>
            //<DoMain></DoMain>
            //</data>
            XmlDocument returnXML = new XmlDocument();
            XmlElement root = returnXML.CreateElement("data");
            returnXML.AppendChild(root);
            XmlElement emailAddress = returnXML.CreateElement("EmailAddress");
            emailAddress.InnerText = this.viewState["_EmailAddress"];
            root.AppendChild(emailAddress);

            XmlElement Username = returnXML.CreateElement("Username");
            Username.InnerText = this.viewState["_Username"];
            root.AppendChild(Username);

            XmlElement Password = returnXML.CreateElement("Password");
            Password.InnerText = this.viewState[ "_Password"];
            root.AppendChild(Password);

            XmlElement EmailType = returnXML.CreateElement("EmailType");
            EmailType.InnerText = this.viewState[ "_Type"];
            root.AppendChild(EmailType);

            XmlElement Host = returnXML.CreateElement("Host");
            Host.InnerText = this.viewState[ "_Host"];
            root.AppendChild(Host);

            switch (emailType)
            {
                case "POP":
                    XmlElement Port = returnXML.CreateElement("Port");
                    Port.InnerText = this.viewState[ "_Port"];
                    root.AppendChild(Port);

                    XmlElement EnableSSL = returnXML.CreateElement("EnableSSL");
                    EnableSSL.InnerText = this.viewState[ "_EnableSSL"];
                    root.AppendChild(EnableSSL);
                    break;
                case "Exchange":
                    XmlElement DoMain = returnXML.CreateElement("DoMain");
                    DoMain.InnerText = this.viewState[ "_DoMain"];
                    root.AppendChild(DoMain);
                    break;
            }
            return returnXML;
        }

        public void PostbackAction(string command, System.Collections.Specialized.NameValueCollection argument)
        {
            this.viewState = argument;
            this.emailType = this.viewState[ "_Type"];
        }

        #endregion

        #region ISetTaskProperties Members

        public void SetProperties(System.Collections.Generic.Dictionary<string, object> properties)
        {
            if (properties["Status"].ToString() == "Edit")
            {
                this.SetDefaultValue(properties["TaskData"].ToString());
            }
            if (properties.ContainsKey("_EmailAddress"))
                this.viewState["_EmailAddress"] = properties["_EmailAddress"].ToString();
            if (properties.ContainsKey("_Username"))
                this.viewState["_Username"] = properties["_Username"].ToString();
            if (properties.ContainsKey("_Password"))
                this.viewState["_Password"] = properties["_Password"].ToString();
            if (properties.ContainsKey("_Type"))
                this.viewState["_Type"] = properties["_Type"].ToString();
            if (properties.ContainsKey("_Host"))
                this.viewState["_Host"] = properties["_Host"].ToString();
            if (properties.ContainsKey("_Port"))
                this.viewState["_Port"] = properties["_Port"].ToString();
            if (properties.ContainsKey("_EnableSSL"))
                this.viewState["_EnableSSL"] = properties["_EnableSSL"].ToString();
            if (properties.ContainsKey("_DoMain"))
                this.viewState["_DoMain"] = properties["_DoMain"].ToString();

        }

        private void SetDefaultValue(String taskXML)
        {
            //<data>
            //<EmailAddress></EmailAddress>
            //<Username></Username>
            //<Password></Password>
            //<EmailType>POP|Exchange</EmailType>
            //<Host></Host>
            //<Port></Port>
            //<EnableSSL></EnableSSL>
            //<DoMain></DoMain>
            //</data>
            if (taskXML != String.Empty)
            {
                XmlDocument dataXML = new XmlDocument();
                dataXML.LoadXml(taskXML);

                XmlNode EmailAddress = dataXML.GetElementsByTagName("EmailAddress")[0];
                this.viewState["_EmailAddress"] = EmailAddress.InnerText;

                XmlNode Username = dataXML.GetElementsByTagName("Username")[0];
                this.viewState[ "_Username"] = Username.InnerText;

                XmlNode Password = dataXML.GetElementsByTagName("Password")[0];
                this.viewState["_Password"] = Password.InnerText;

                XmlNode EmailType = dataXML.GetElementsByTagName("EmailType")[0];
                this.viewState["_Type"] = EmailType.InnerText;

                XmlNode Host = dataXML.GetElementsByTagName("Host")[0];
                this.viewState[ "_Host"] = Host.InnerText;
                this.emailType = EmailType.InnerText;
                switch (EmailType.InnerText)
                {
                    case "POP":
                        XmlNode Port = dataXML.GetElementsByTagName("Port")[0];
                        this.viewState[ "_Port"] = Port.InnerText;

                        XmlNode EnableSSL = dataXML.GetElementsByTagName("EnableSSL")[0];
                        this.viewState[ "_EnableSSL"] = EnableSSL.InnerText;
                        break;
                    case "Exchange":
                        XmlNode DoMain = dataXML.GetElementsByTagName("DoMain")[0];
                        this.viewState[ "_DoMain"] = DoMain.InnerText;
                        break;
                }
            }
        }
        #endregion
        class emailMessage
        {
            public string subject = "";
            public DateTime date = DateTime.Now;
            public string displayname = "";
            public string from = "";
            public string body = "";
            public int mailindex = -1;
            public string displaytoname = "";
            public string to = "";
            public string attachments = "";
            public byte[] attachmentByte = null;
            public string attachmentName = "";
        }
        class Attachment
        {
            public byte[] attachmentByte = null;
            public string attachmentName = "";
            public int length;
        }
    }
}

posted on 2008-07-28 17:29  杨林  阅读(378)  评论(0编辑  收藏  举报