Ejemplo n.º 1
0
 public static bool IsSpamMail(Mail_Message mail)
 {
     if( spamHeader == null )
         LoadSpamHeader();
     MIME_h[] value;
     foreach(string header in spamHeader.Keys)
     {
         value = mail.Header[header];
         if( value != null && value.Length > 0 && value[0] != null )
         {
             if( String.Compare(spamHeader[header], value[0].ValueToString().Trim(), true) == 0 )
                 return true;
         }
     }
     return false;
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Parses mail message from the specified stream.
        /// </summary>
        /// <param name="stream">Stream from where to parse mail message. Parsing starts from current stream position.</param>
        /// <param name="headerEncoding">Header reading encoding. If not sure UTF-8 is recommended.</param>
        /// <returns>Returns parsed mail message.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> or <b>headerEncoding</b> is null.</exception>
        public static new Mail_Message ParseFromStream(Stream stream,Encoding headerEncoding)
        {
            if(stream == null){
                throw new ArgumentNullException("stream");
            }
            if(headerEncoding == null){
                throw new ArgumentNullException("headerEncoding");
            }

            Mail_Message retVal = new Mail_Message();
            retVal.Parse(new SmartStream(stream,false),headerEncoding,new MIME_h_ContentType("text/plain"));

            return retVal;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Sends message by using specified smart host.
        /// </summary>
        /// <param name="host">Host name or IP address.</param>
        /// <param name="port">Host port.</param>
        /// <param name="ssl">Specifies if connected via SSL.</param>
        /// <param name="message">Mail message to send.</param>
        /// <exception cref="ArgumentNullException">Is raised when argument <b>host</b> or <b>message</b> is null.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the method arguments has invalid value.</exception>
        /// <exception cref="SMTP_ClientException">Is raised when SMTP server returns error.</exception>
        public static void QuickSendSmartHost(string host,int port,bool ssl,Mail_Message message)
        {
            if(message == null){
                throw new ArgumentNullException("message");
            }

            string from = "";
            if(message.From != null && message.From.Count > 0){
                from = ((Mail_t_Mailbox)message.From[0]).Address;
            }

            List<string> recipients = new List<string>();
            if(message.To != null){
                Mail_t_Mailbox[] addresses = message.To.Mailboxes;
                foreach(Mail_t_Mailbox address in addresses){
                    recipients.Add(address.Address);
                }
            }
            if(message.Cc != null){
                Mail_t_Mailbox[] addresses = message.Cc.Mailboxes;
                foreach(Mail_t_Mailbox address in addresses){
                    recipients.Add(address.Address);
                }
            }
            if(message.Bcc != null){
                Mail_t_Mailbox[] addresses = message.Bcc.Mailboxes;
                foreach(Mail_t_Mailbox address in addresses){
                    recipients.Add(address.Address);
                }

                // We must hide BCC
                message.Bcc.Clear();
            }

            foreach(string recipient in recipients){
                MemoryStream ms = new MemoryStream();
                message.ToStream(ms,new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q,Encoding.UTF8),Encoding.UTF8);
                ms.Position = 0;
                QuickSendSmartHost(null,host,port,ssl,null,null,from,new string[]{recipient},ms);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="mm">邮件对象</param>
        /// <param name="from">发送人</param>
        /// <param name="to">接收人</param>
        private void send(Mail_Message mm, ASObject from, string[] to)
        {
            using (MemoryStreamEx stream = new MemoryStreamEx(32000))
            {
                MIME_Encoding_EncodedWord headerwordEncoder = new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8);
                mm.ToStream(stream, headerwordEncoder, Encoding.UTF8);
                stream.Position = 0;

                SMTP_Client.QuickSendSmartHost(null, from.getString("send_address", "stmp.sina.com"), from.getInt("send_port", 25),
                    from.getBoolean("is_send_ssl", false), from.getString("account"), PassUtil.Decrypt(from.getString("password")),
                    from.getString("account"), to, stream);
            }
        }
Ejemplo n.º 5
0
        void btnSave_Click(object sender, RoutedEventArgs e)
        {
            using (MemoryStreamEx stream = new MemoryStreamEx(32000))
            {
                try
                {
                    if (Mail_Message == null)
                        Mail_Message = createMessage();

                    updateMessage(Mail_Message);
                    MIME_Encoding_EncodedWord headerwordEncoder = new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8);
                    Mail_Message.ToStream(stream, headerwordEncoder, Encoding.UTF8);

                    if (_saveMail == null)
                    {
                        //存放邮件到草稿目录 DRAFT
                        StringBuilder sb = new StringBuilder();
                        string uuid = Guid.NewGuid().ToString();
                        sb.Append(MailReceiveWorker.getFilePath(uuid)).Append("/").Append(uuid).Append(".eml");
                        string file = sb.ToString();
                        DirectoryInfo dir = Directory.GetParent(store_path + file);
                        if (!dir.Exists)
                            dir.Create();

                        Mail_Message.ToFile(store_path + file, headerwordEncoder, Encoding.UTF8);
                        _saveMail = saveMail(null, Mail_Message, uuid, file, (int)DBWorker.MailType.DraftMail, "DRAFT");

                        MailWorker.instance.dispatchMailEvent(MailWorker.Event.Create, _saveMail, null);
                        MailWorker.instance.syncUserMail(_saveMail);
                    }
                    else
                    {
                        string file = _saveMail["mail_file"] as string;
                        string uuid = _saveMail["uuid"] as string;
                        Mail_Message.ToFile(store_path + file, headerwordEncoder, Encoding.UTF8);
                        _saveMail = saveMail(_saveMail, Mail_Message, uuid, file, (int)DBWorker.MailType.DraftMail, "DRAFT");

                        MailWorker.instance.dispatchMailEvent(MailWorker.Event.Update, _saveMail, getUpdateFields().ToArray());
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.Write(ex.StackTrace);
                    this.Dispatcher.BeginInvoke((System.Action)delegate
                    {
                        ime.controls.MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
                }
            }
        }
Ejemplo n.º 6
0
        private ASObject saveMail(Mail_Message m, string uid, string mail_uid, string file)
        {
            workInfo.IsNewMail = true;
            DirectoryInfo dirinfo = Directory.GetParent(store_path + file);
            string dir = dirinfo.FullName + "/" + uid + ".parts";
            Directory.CreateDirectory(dir);

            ASObject record = new ASObject();

            record.Add("uuid", uid);
            record.Add("owner_user_id", wos.library.Desktop.instance.loginedPrincipal.id);
            try
            {
                string subject = m.Subject;
                if (subject == null)
                    subject = "";
                else if (subject.IndexOf("&#") != -1)
                {
                    subject = HttpUtility.HtmlDecode(subject);
                }
                record.Add("subject", subject);
            }
            catch (Exception)
            {
                record.Add("subject", "");
            }
            try
            {
                record.Add("sender", m.Sender == null ? "" : m.Sender.ToString());
            }
            catch (Exception)
            {
                record.Add("sender", "");
            }
            try
            {
                record.Add("mail_to", m.To == null ? "" : m.To.ToString());
                if (m.To != null && m.To.Mailboxes.Count() > 0)
                    record.Add("mail_to_label", getMailBoxLabel(m.To.Mailboxes[0]));
            }
            catch (Exception)
            {
                record.Add("mail_to", "");
            }
            try
            {
                record.Add("reply_to", m.ReplyTo == null ? "" : m.ReplyTo.ToString());
            }
            catch (Exception)
            {
                record.Add("reply_to", "");
            }
            try
            {
                record.Add("mail_from", m.From == null ? "" : m.From.ToString());
                if (m.From != null && m.From.Count > 0)
                {
                    record.Add("mail_from_label", getMailBoxLabel(m.From[0]));
                    record.Add("contact_mail", m.From[0].Address);
                }
            }
            catch (Exception)
            {
                record.Add("mail_from", "");
                record.Add("contact_mail", "");
            }
            //阅读回折
            if (m.DispositionNotificationTo != null && m.DispositionNotificationTo.Count > 0)
                record.Add("flags", "RECEIPT");
            else
                record.Add("flags", "RECENT");

            try
            {
                if (Setting.IsSpamMail(m))
                {
                    record.Add("mail_type", (int)DBWorker.MailType.SpamMail);
                    record.Add("folder", "SPAM");
                }
                else
                {
                    record.Add("mail_type", (int)DBWorker.MailType.RecvMail);
                    record.Add("folder", "INBOX");
                }
            }
            catch (Exception)
            {
                record.Add("mail_type", (int)DBWorker.MailType.RecvMail);
                record.Add("folder", "INBOX");
            }
            try
            {
                record.Add("cc", m.Cc == null ? "" : m.Cc.ToString());
            }
            catch (Exception)
            {
                record.Add("cc", "");
            }
            try
            {
                record.Add("bcc", m.Bcc == null ? "" : m.Bcc.ToString());
            }
            catch (Exception)
            {
                record.Add("bcc", "");
            }

            record.Add("message_id", m.MessageID == null ? uid : m.MessageID);
            record.Add("create_time", DateTimeUtil.now());
            record.Add("mail_date", m.Date == DateTime.MinValue ? DateTimeUtil.now() : m.Date);
            record.Add("send_time", null);
            record.Add("mail_account", mailAccount.account);
            record.Add("mail_file", file);
            record.Add("reply_for", null);
            record.Add("reply_header", null);
            record.Add("mail_uid", mail_uid);
            record.Add("client_or_server", "client");
            record.Add("is_synced", (short)0);
            record.Add("is_handled", is_handled);
            record.Add("priority", m.Priority);
            if (m.Received != null && m.Received.Count() > 0)
            {
                try
                {
                    if (m.Received[0].From_TcpInfo != null)
                        record.Add("ip_from", m.Received[0].From_TcpInfo.IP.ToString());
                }
                catch (Exception)
                {
                }
            }
            return record;
        }
Ejemplo n.º 7
0
        private ASObject saveMail(ASObject record, Mail_Message m, string uid, string file, int mail_type, string folder)
        {
            if (record == null)
                record = new ASObject();

            record["uuid"] = uid;
            if(String.IsNullOrWhiteSpace(record.getString("owner_user_id")))
                record["owner_user_id"] = wos.library.Desktop.instance.loginedPrincipal.id;
            try
            {
                string subject = m.Subject;
                if (subject == null)
                    subject = "";
                else if (subject.IndexOf("&#") != -1)
                {
                    subject = HttpUtility.HtmlDecode(subject);
                }
                record["subject"] = subject;
            }
            catch (Exception)
            {
                record["subject"] = "";
            }
            record["sender"] = m.Sender == null ? "" : m.Sender.ToString();
            try
            {
                record["mail_to"] = m.To == null ? "" : m.To.ToString();
                if (m.To != null && m.To.Mailboxes.Count() > 0)
                    record["mail_to_label"] = getMailBoxLabel(m.To.Mailboxes[0]);
            }
            catch (Exception)
            {
                record["mail_to"] = "";
            }
            record["reply_to"] = m.ReplyTo == null ? "" : m.ReplyTo.ToString();
            try
            {
                record["mail_from"] = m.From == null ? "" : m.From.ToString();
                if (m.From != null && m.From.Count > 0)
                {
                    record["mail_from_label"] = getMailBoxLabel(m.From[0]);
                    record["contact_mail"] = m.From[0].Address;
                }
            }
            catch (Exception)
            {
                record["mail_from"] = "";
                record["contact_mail"] = "";
            }
            record["flags"] = "RECENT";
            record["mail_type"] = mail_type;
            record["folder"] = folder;
            record["cc"] = m.Cc == null ? "" : m.Cc.ToString();
            record["bcc"] = m.Bcc == null ? "" : m.Bcc.ToString();
            record["is_seen"] = true;
            record["message_id"] = m.MessageID;
            record["create_time"] = DateTimeUtil.now();
            if(String.IsNullOrWhiteSpace(record.getString("mail_date")))
                record["mail_date"] = DateTimeUtil.now();
            if (mail_type == (int)DBWorker.MailType.SendMail)
                record["send_time"] = DateTimeUtil.now();
            if (from != null)
                record["mail_account"] = from.getString("account");
            record["mail_file"] = file;
            record["reply_for"] = null;
            record["reply_header"] = null;
            record["mail_uid"] = uid;
            record["client_or_server"] = "client";
            record["is_synced"] = (short)0;
            record["priority"] = m.Priority;
            if (m.Received != null && m.Received.Count() > 0)
            {
                try
                {
                    if (m.Received[0].From_TcpInfo != null)
                        record["ip_from"] = m.Received[0].From_TcpInfo.IP.ToString();
                }
                catch (Exception)
                {
                }
            }
            return record;
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 发送阅读回折邮件
        /// </summary>
        /// <param name="sHtmlText">邮件内容</param>
        /// <param name="from">发送人</param>
        /// <param name="to">接收人</param>
        public void sendReceiptMail(string sHtmlText, string subject, ASObject from, string[] to)
        {
            using (MemoryStreamEx stream = new MemoryStreamEx(32000))
            {
                Mail_Message m = new Mail_Message();
                m.MimeVersion = "1.0";
                m.Date = DateTime.Now;
                m.MessageID = MIME_Utils.CreateMessageID();

                m.Subject = subject;
                StringBuilder sb = new StringBuilder();
                foreach (string p in to)
                {
                    if (sb.Length > 0)
                        sb.Append(",");
                    sb.Append(p);
                }
                m.To = Mail_t_AddressList.Parse(sb.ToString());

                //--- multipart/alternative -----------------------------------------------------------------------------------------
                MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative);
                contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
                MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative);
                m.Body = multipartAlternative;

                //--- text/plain ----------------------------------------------------------------------------------------------------
                MIME_Entity entity_text_plain = new MIME_Entity();
                MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
                entity_text_plain.Body = text_plain;
                text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, sHtmlText);
                multipartAlternative.BodyParts.Add(entity_text_plain);

                //--- text/html ------------------------------------------------------------------------------------------------------
                MIME_Entity entity_text_html = new MIME_Entity();
                MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html);
                entity_text_html.Body = text_html;
                text_html.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, sHtmlText);
                multipartAlternative.BodyParts.Add(entity_text_html);

                MIME_Encoding_EncodedWord headerwordEncoder = new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8);
                m.ToStream(stream, headerwordEncoder, Encoding.UTF8);
                stream.Position = 0;

                SMTP_Client.QuickSendSmartHost(null, from.getString("send_address", "stmp.sina.com"), from.getInt("send_port", 25),
                    from.getBoolean("is_send_ssl", false), from.getString("account"), PassUtil.Decrypt(from.getString("password")),
                    from.getString("account"), to, stream);
            }
        }
Ejemplo n.º 9
0
        private string getTransmitVm(ASObject mail, Mail_Message m)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<br/><br/><br/><br/><hr/>-------- 转发邮件信息 --------<br/>");
            DateTime date = (DateTime)mail["mail_date"];
            if (date == null)
                date = DateTime.Now;

            sb.Append("发件人: ").Append(mail["mail_from"]).Append("<br/>");
            sb.Append("发送日期: ").Append(date.ToString("yyyy-MM-dd HH:mm:ss")).Append("<br/>");
            sb.Append("收件人: ").Append(mail["mail_to"]).Append("<br/>");
            Mail_t_AddressList addresses = m.Cc;
            if (addresses != null)
            {
                sb.Append("抄送人: ");
                foreach (Mail_t_Mailbox mailbox in addresses.Mailboxes)
                {
                    sb.Append(mailbox.Address).Append(";");
                }
                if (sb.ToString().LastIndexOf(";") != -1)
                    sb.Remove(sb.ToString().LastIndexOf(";"), 1);
                sb.Append("<br/>");
            }

            sb.Append("主题: ").Append(mail["subject"]).Append("<br/>");

            return sb.ToString();
        }
Ejemplo n.º 10
0
        private string parseMIMEContent(Mail_Message m, string dir)
        {
            MIME_Entity[] entities = m.GetAllEntities(true);
            if (entities == null)
                return "";
            Map<string, string> content_id_file = new Map<string, string>();
            StringBuilder textHtml = new StringBuilder();
            foreach (MIME_Entity e in entities)
            {
                try
                {
                    if (e.Body.MediaType.ToLower() == MIME_MediaTypes.Text.html)
                        continue;
                    else if (e.Body.MediaType.ToLower() == MIME_MediaTypes.Text.plain)
                        continue;
                    else if (e.Body is MIME_b_SinglepartBase)
                    {
                        MIME_b_SinglepartBase p = (MIME_b_SinglepartBase)e.Body;

                        string fPath = "";
                        string fileName = e.ContentType.Param_Name;
                        if (fileName == null)
                            fileName = Guid.NewGuid().ToString();
                        fileName = fileName.Replace(' ', '_');
                        fPath = System.IO.Path.Combine(dir, fileName);
                        if (!File.Exists(fPath))
                        {
                            using (Stream data = p.GetDataStream())
                            {
                                using (FileStream afs = File.Create(fPath))
                                {
                                    Net_Utils.StreamCopy(data, afs, 4096);
                                }
                            }
                        }

                        string contentId = e.ContentID;
                        if (!String.IsNullOrEmpty(contentId))
                        {
                            contentId = contentId.Trim();
                            if (contentId.StartsWith("<"))
                                contentId = contentId.Substring(1);
                            if (contentId.EndsWith(">"))
                                contentId = contentId.Substring(0, contentId.Length - 1);
                            content_id_file.Add(contentId, fPath);
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }
            foreach (MIME_Entity e in entities)
            {
                try
                {
                    if (e.Body.MediaType.ToLower() == MIME_MediaTypes.Text.html)
                    {
                        string html = ((MIME_b_Text)e.Body).Text;

                        //处理html中的内嵌图片
                        if (content_id_file.Count > 0)
                        {
                            foreach (string key in content_id_file.Keys)
                            {
                                html = html.Replace("cid:" + key, content_id_file[key]);
                            }
                        }

                        textHtml.Append(html);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }

            return textHtml.ToString();
        }
Ejemplo n.º 11
0
        private string getReplyVm(ASObject mail, Mail_Message m)
        {
            StringBuilder sb = new StringBuilder();
            DateTime date = (DateTime)mail["mail_date"];
            if (date == null)
                date = DateTime.Now;
            sb.Append("<br/><br/><br/><br/><hr/><div style=\"line-height:1.7;color:#000000;font-size:14px;font-family:arial\">");
            sb.Append("在 ").Append(date.ToString("yyyy-MM-dd HH:mm:ss")).Append(",").Append(mail["mail_from"]).Append(" 写道:").Append("<br/>");
            sb.Append("</div>");

            return sb.ToString();
        }
Ejemplo n.º 12
0
        private Mail_Message createMessage()
        {
            Mail_Message m = new Mail_Message();
            m.MimeVersion = "1.0";
            m.Date = DateTime.Now;
            m.MessageID = MIME_Utils.CreateMessageID();

            updateMessage(m);
            return m;
        }
Ejemplo n.º 13
0
        void btnSendMail_Click(object sender, RoutedEventArgs e)
        {
            using (MemoryStreamEx stream = new MemoryStreamEx(32000))
            {
                try
                {
                    if (String.IsNullOrWhiteSpace(txtTo.Text))
                        throw new Exception("收件人不能为空!");

                    if (Mail_Message == null)
                        Mail_Message = createMessage();

                    updateMessage(Mail_Message);

                    if ((Mail_Type == MailType.AllReply || Mail_Type == MailType.Reply) && _mail != null)
                        Mail_Message.InReplyTo = _mail["message_id"] as string;

                    MIME_Encoding_EncodedWord headerwordEncoder = new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8);
                    Mail_Message.ToStream(stream, headerwordEncoder, Encoding.UTF8);

                    int mail_type = (int)DBWorker.MailType.OutboxMail;
                    string folder = "OUTBOX";
                    if (reviewer != null)
                    {
                        mail_type = (int)DBWorker.MailType.SendMail;
                        folder = "DSBOX";
                    }
                    if (_saveMail == null)
                    {
                        StringBuilder sb = new StringBuilder();
                        string uuid = Guid.NewGuid().ToString();
                        sb.Append(MailReceiveWorker.getFilePath(uuid)).Append("/").Append(uuid).Append(".eml");
                        string file = sb.ToString();
                        DirectoryInfo dir = Directory.GetParent(store_path + file);
                        if (!dir.Exists)
                            dir.Create();

                        Mail_Message.ToFile(store_path + file, headerwordEncoder, Encoding.UTF8);
                        _saveMail = saveMail(null, Mail_Message, uuid, file, mail_type, folder);
                        if (mail_type == (int)DBWorker.MailType.SendMail)
                        {
                            _saveMail["reviewer_id"] = reviewer.getLong("id");
                            _saveMail["reviewer_name"] = reviewer.getString("name");
                            _saveMail["operator_id"] = Desktop.instance.loginedPrincipal.id;
                            _saveMail["operator_name"] = Desktop.instance.loginedPrincipal.name;
                        }
                        MailWorker.instance.dispatchMailEvent(MailWorker.Event.Create, _saveMail, null);

                        if (mail_type == (int)DBWorker.MailType.SendMail)
                        {
                            MailWorker.instance.syncUserMail(_saveMail);
                        }
                    }
                    else
                    {
                        List<string> list = getUpdateFields();
                        string file = _saveMail["mail_file"] as string;
                        string uuid = _saveMail["uuid"] as string;
                        Mail_Message.ToFile(store_path + file, headerwordEncoder, Encoding.UTF8);
                        _saveMail = saveMail(_saveMail, Mail_Message, uuid, file, mail_type, folder);
                        if (mail_type == (int)DBWorker.MailType.SendMail)
                        {
                            _saveMail["reviewer_id"] = reviewer.getLong("id");
                            _saveMail["reviewer_name"] = reviewer.getString("name");
                            list.Add("reviewer_id");
                            list.Add("reviewer_name");
                            if (String.IsNullOrWhiteSpace(_saveMail.getString("operator_id")))
                            {
                                _saveMail["operator_id"] = Desktop.instance.loginedPrincipal.id;
                                _saveMail["operator_name"] = Desktop.instance.loginedPrincipal.name;
                                list.Add("operator_id");
                                list.Add("operator_name");
                            }
                        }
                        MailWorker.instance.dispatchMailEvent(MailWorker.Event.Update, _saveMail, list.ToArray());
                    }

                    if (Mail_Type == MailType.AllReply || Mail_Type == MailType.Reply)
                    {
                        _mail["handle_action"] = 2;
                        _mail["is_handled"] = true;

                        MailWorker.instance.dispatchMailEvent(MailWorker.Event.Update, _mail, new string[] { "handle_action", "is_handled" });
                    }
                    if (mail_type == (int)DBWorker.MailType.OutboxMail)
                    {
                        MailSendWorker.instance.AddMail(_saveMail);
                        MailSendWorker.instance.Start();
                    }

                    this.Close();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.Write(ex.StackTrace);
                    this.Dispatcher.BeginInvoke((System.Action)delegate
                    {
                        ime.controls.MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
                }
            }
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Constructs FETCH BODY and BODYSTRUCTURE response.
 /// </summary>
 /// <param name="message">Mail message.</param>
 /// <param name="bodystructure">Specifies if to construct BODY or BODYSTRUCTURE.</param>
 /// <returns></returns>
 public static string ConstructBodyStructure(Mail_Message message,bool bodystructure)
 {
     if(bodystructure){
         return "BODYSTRUCTURE " + ConstructParts(message,bodystructure);
     }
     else{
         return "BODY " + ConstructParts(message,bodystructure);
     }
 }
Ejemplo n.º 15
0
        private void showMail(ASObject mail)
        {
            try
            {
                if (Mail_Type == MailType.Dsbox)
                {
                    btnSave.IsEnabled = false;
                    btnAudit.IsEnabled = false;
                }

                txtTo.TextChanged -= txtTo_TextChanged;
                cboFrom.SelectionChanged -= cboFrom_SelectionChanged;

                string mail_account = mail["mail_account"] as string;
                from = MailSendWorker.instance.findAccount(mail_account);

                if (from == null)
                {
                    txtTo.TextChanged += txtTo_TextChanged;
                    cboFrom.SelectionChanged += cboFrom_SelectionChanged;
                }

                string file = mail.getString("mail_file");
                StringBuilder sb = new StringBuilder();
                Mail_Message = MailWorker.instance.ParseMail(file);
                if (Mail_Type == MailType.Transmit)
                    txtSubject.Text = "Fw:" + mail["subject"] as string;
                else if (Mail_Type == MailType.Reply || Mail_Type == MailType.AllReply)
                {
                    txtSubject.Text = "Re:" + mail["subject"] as string;
                }
                else
                    txtSubject.Text = mail["subject"] as string;

                sb.Clear();
                Mail_t_AddressList addresses = Mail_Message.Cc;
                if (addresses != null)
                {
                    foreach (Mail_t_Mailbox mailbox in addresses.Mailboxes)
                    {
                        sb.Append(mailbox.Address).Append(";");
                    }
                    if (sb.ToString().LastIndexOf(";") != -1)
                        sb.Remove(sb.ToString().LastIndexOf(";"), 1);

                    txtCc.Text = sb.ToString();
                }

                if (Mail_Type == MailType.Draft || Mail_Type == MailType.Dsbox)
                    txtTo.Text = mail["mail_to"] as string;
                else if (Mail_Type != MailType.Transmit)
                    txtTo.Text = mail["contact_mail"] as string;

                if (Mail_Type != MailType.Transmit)
                {
                    //审核人
                    if (mail.ContainsKey("reviewer_id") && !String.IsNullOrWhiteSpace(mail.getString("reviewer_id")))
                    {
                        txtAudit.Text = mail.getString("reviewer_name");
                    }
                }

                sb.Clear();
                string uid = mail["uuid"] as string;
                DirectoryInfo dirinfo = Directory.GetParent(store_path + file);
                string dir = dirinfo.FullName + "/" + uid + ".parts";

                if (Mail_Type == MailType.Transmit)
                {
                    sb.Append(getTransmitVm(mail, Mail_Message));
                    sb.Append("<blockquote id=\"isReplyContent\" style=\"PADDING-LEFT: 1ex; MARGIN: 0px 0px 0px 0.8ex; BORDER-LEFT: #ccc 1px solid\">");
                }
                else if (Mail_Type == MailType.Reply || Mail_Type == MailType.AllReply)
                {
                    sb.Append(getReplyVm(mail, Mail_Message));
                    sb.Append("<blockquote id=\"isReplyContent\" style=\"PADDING-LEFT: 1ex; MARGIN: 0px 0px 0px 0.8ex; BORDER-LEFT: #ccc 1px solid\">");
                }

                string textHtml = parseMIMEContent(Mail_Message, dir);
                sb.Append(textHtml);

                if (Mail_Type == MailType.Transmit || Mail_Type == MailType.Reply || Mail_Type == MailType.AllReply)
                {
                    sb.Append("</blockquote>");
                }

                htmlEditor.ContentHtml = sb.ToString();

                if (Mail_Type == MailType.Draft || Mail_Type == MailType.Dsbox)
                {
                    _saveMail = _mail;
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.Write(e.StackTrace);
                ime.controls.MessageBox.Show(e.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Construct secified mime entity ENVELOPE string.
        /// </summary>
        /// <param name="entity">Mail message.</param>
        /// <returns></returns>
        public static string ConstructEnvelope(Mail_Message entity)
        {
            /* RFC 3501 7.4.2
                ENVELOPE
                    A parenthesized list that describes the envelope structure of a
                    message.  This is computed by the server by parsing the
                    [RFC-2822] header into the component parts, defaulting various
                    fields as necessary.

                    The fields of the envelope structure are in the following
                    order: date, subject, from, sender, reply-to, to, cc, bcc,
                    in-reply-to, and message-id.  The date, subject, in-reply-to,
                    and message-id fields are strings.  The from, sender, reply-to,
                    to, cc, and bcc fields are parenthesized lists of address
                    structures.

                    An address structure is a parenthesized list that describes an
                    electronic mail address.  The fields of an address structure
                    are in the following order: personal name, [SMTP]
                    at-domain-list (source route), mailbox name, and host name.

                    [RFC-2822] group syntax is indicated by a special form of
                    address structure in which the host name field is NIL.  If the
                    mailbox name field is also NIL, this is an end of group marker
                    (semi-colon in RFC 822 syntax).  If the mailbox name field is
                    non-NIL, this is a start of group marker, and the mailbox name
                    field holds the group name phrase.

                    If the Date, Subject, In-Reply-To, and Message-ID header lines
                    are absent in the [RFC-2822] header, the corresponding member
                    of the envelope is NIL; if these header lines are present but
                    empty the corresponding member of the envelope is the empty
                    string.

                        Note: some servers may return a NIL envelope member in the
                        "present but empty" case.  Clients SHOULD treat NIL and
                        empty string as identical.

                        Note: [RFC-2822] requires that all messages have a valid
                        Date header.  Therefore, the date member in the envelope can
                        not be NIL or the empty string.

                        Note: [RFC-2822] requires that the In-Reply-To and
                        Message-ID headers, if present, have non-empty content.
                        Therefore, the in-reply-to and message-id members in the
                        envelope can not be the empty string.

                    If the From, To, cc, and bcc header lines are absent in the
                    [RFC-2822] header, or are present but empty, the corresponding
                    member of the envelope is NIL.

                    If the Sender or Reply-To lines are absent in the [RFC-2822]
                    header, or are present but empty, the server sets the
                    corresponding member of the envelope to be the same value as
                    the from member (the client is not expected to know to do
                    this).

                        Note: [RFC-2822] requires that all messages have a valid
                        From header.  Therefore, the from, sender, and reply-to
                        members in the envelope can not be NIL.

                    ENVELOPE ("date" "subject" from sender reply-to to cc bcc "in-reply-to" "messageID")
            */

            // NOTE: all header fields and parameters must in ENCODED form !!!

            MIME_Encoding_EncodedWord wordEncoder = new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.B,Encoding.UTF8);
            wordEncoder.Split = false;

            StringBuilder retVal = new StringBuilder();
            retVal.Append("ENVELOPE (");

            // date
            try{
                if(entity.Date != DateTime.MinValue){
                    retVal.Append(TextUtils.QuoteString(MIME_Utils.DateTimeToRfc2822(entity.Date)));
                }
                else{
                    retVal.Append("NIL");
                }
            }
            catch{
                retVal.Append("NIL");
            }

            // subject
            if(entity.Subject != null){
                //retVal.Append(" " + TextUtils.QuoteString(wordEncoder.Encode(entity.Subject)));
                string val = wordEncoder.Encode(entity.Subject);
                retVal.Append(" {" + val.Length + "}\r\n" + val);
            }
            else{
                retVal.Append(" NIL");
            }

            // from
            if(entity.From != null && entity.From.Count > 0){
                retVal.Append(" " + ConstructAddresses(entity.From.ToArray(),wordEncoder));
            }
            else{
                retVal.Append(" NIL");
            }

            // sender
            //	NOTE: There is confusing part, according rfc 2822 Sender: is MailboxAddress and not AddressList.
            if(entity.Sender != null){
                retVal.Append(" (");

                retVal.Append(ConstructAddress(entity.Sender,wordEncoder));

                retVal.Append(")");
            }
            else{
                retVal.Append(" NIL");
            }

            // reply-to
            if(entity.ReplyTo != null){
                retVal.Append(" " + ConstructAddresses(entity.ReplyTo.Mailboxes,wordEncoder));
            }
            else{
                retVal.Append(" NIL");
            }

            // to
            if(entity.To != null && entity.To.Count > 0){
                retVal.Append(" " + ConstructAddresses(entity.To.Mailboxes,wordEncoder));
            }
            else{
                retVal.Append(" NIL");
            }

            // cc
            if(entity.Cc != null && entity.Cc.Count > 0){
                retVal.Append(" " + ConstructAddresses(entity.Cc.Mailboxes,wordEncoder));
            }
            else{
                retVal.Append(" NIL");
            }

            // bcc
            if(entity.Bcc != null && entity.Bcc.Count > 0){
                retVal.Append(" " + ConstructAddresses(entity.Bcc.Mailboxes,wordEncoder));
            }
            else{
                retVal.Append(" NIL");
            }

            // in-reply-to
            if(entity.InReplyTo != null){
                retVal.Append(" " + TextUtils.QuoteString(wordEncoder.Encode(entity.InReplyTo)));
            }
            else{
                retVal.Append(" NIL");
            }

            // message-id
            if(entity.MessageID != null){
                retVal.Append(" " + TextUtils.QuoteString(wordEncoder.Encode(entity.MessageID)));
            }
            else{
                retVal.Append(" NIL");
            }

            retVal.Append(")");

            return retVal.ToString();
        }
Ejemplo n.º 17
0
        private void updateMessage(Mail_Message m)
        {
            if (from != null)
                m.From = Mail_t_MailboxList.Parse(from.getString("account"));
            m.To = Mail_t_AddressList.Parse(txtTo.Text);
            if (!String.IsNullOrWhiteSpace(txtSubject.Text))
                m.Subject = txtSubject.Text;
            if (!String.IsNullOrWhiteSpace(txtCc.Text))
                m.Cc = Mail_t_AddressList.Parse(txtCc.Text.Trim());

            if (Receipt.IsChecked == true)
            {
                m.DispositionNotificationTo = Mail_t_MailboxList.Parse(from.getString("account"));
            }
            if (Importance.IsChecked == true)
            {
                m.Priority = "urgent";
            }

            string sHtmlText = htmlEditor.ContentHtml;
            List<string> sUrlList = getHtmlImageUrlList(sHtmlText);

            if (sUrlList.Count > 0 || attachments.Children.OfType<AttachmentItem>().Count() > 0)
            {
                //--- multipart/mixed -------------------------------------------------------------------------------------------------
                MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed);
                contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
                MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed);
                m.Body = multipartMixed;

                //--- multipart/alternative -----------------------------------------------------------------------------------------
                MIME_Entity entity_mulipart_alternative = new MIME_Entity();
                MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative);
                contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
                MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative);
                entity_mulipart_alternative.Body = multipartAlternative;
                multipartMixed.BodyParts.Add(entity_mulipart_alternative);

                //--- text/plain ----------------------------------------------------------------------------------------------------
                MIME_Entity entity_text_plain = new MIME_Entity();
                MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
                entity_text_plain.Body = text_plain;
                text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, txtEditor.Text);
                multipartAlternative.BodyParts.Add(entity_text_plain);

                // Create attachment etities: --- applactation/octet-stream -------------------------
                foreach (AttachmentItem item in attachments.Children.OfType<AttachmentItem>())
                {
                    multipartMixed.BodyParts.Add(Mail_Message.CreateAttachment(item.File));
                }

                foreach (string url in sUrlList)
                {
                    MIME_Entity img_entity = Mail_Message.CreateImage(url);
                    string contentID = Guid.NewGuid().ToString().Replace("-", "$");
                    img_entity.ContentID = "<" + contentID + ">";
                    sHtmlText = sHtmlText.Replace(url, "cid:" + contentID);
                    multipartMixed.BodyParts.Add(img_entity);
                }

                //--- text/html ------------------------------------------------------------------------------------------------------
                MIME_Entity entity_text_html = new MIME_Entity();
                MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html);
                entity_text_html.Body = text_html;
                text_html.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, sHtmlText);
                multipartAlternative.BodyParts.Add(entity_text_html);
            }
            else
            {
                //--- multipart/alternative -----------------------------------------------------------------------------------------
                MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative);
                contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
                MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative);
                m.Body = multipartAlternative;

                //--- text/plain ----------------------------------------------------------------------------------------------------
                MIME_Entity entity_text_plain = new MIME_Entity();
                MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
                entity_text_plain.Body = text_plain;
                text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, txtEditor.Text);
                multipartAlternative.BodyParts.Add(entity_text_plain);

                //--- text/html ------------------------------------------------------------------------------------------------------
                MIME_Entity entity_text_html = new MIME_Entity();
                MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html);
                entity_text_html.Body = text_html;
                text_html.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, sHtmlText);
                multipartAlternative.BodyParts.Add(entity_text_html);
            }
        }
Ejemplo n.º 18
0
        private void parseMIMEContent(Mail_Message m, string uid, string dir, ASObject record)
        {
            XmlDocument doc = new XmlDocument();
            XmlElement xml = doc.CreateElement("message");
            doc.AppendChild(xml);

            StringBuilder attachments = new StringBuilder();
            MIME_Entity[] entities = m.GetAllEntities(true);

            Map<string, string> content_id_file = new Map<string, string>();
            StringBuilder textHtml = new StringBuilder();
            textHtml.Append(@"<html><head><meta http-equiv=""content-type"" content=""text/html; charset=utf-8""></head><body>");
            bool hasText = false;

            foreach (MIME_Entity e in entities)
            {
                try
                {
                    if (e.Body.MediaType.ToLower() == MIME_MediaTypes.Text.html)
                        continue;
                    else if (e.Body.MediaType.ToLower() == MIME_MediaTypes.Text.plain)
                        continue;
                    else if (e.Body is MIME_b_SinglepartBase)
                    {
                        MIME_b_SinglepartBase p = (MIME_b_SinglepartBase)e.Body;
                        Stream data = p.GetDataStream();
                        string fPath = "";
                        string fileName = e.ContentType.Param_Name;
                        if (fileName == null)
                            fileName = Guid.NewGuid().ToString();
                        else
                            attachments.Append(fileName).Append(";");
                        fileName = fileName.Replace(' ', '_');
                        fPath = System.IO.Path.Combine(dir, fileName);
                        using (FileStream afs = File.Create(fPath))
                        {
                            Net_Utils.StreamCopy(data, afs, 4096);
                        }
                        data.Close();

                        string contentId = e.ContentID;
                        if (!String.IsNullOrEmpty(contentId))
                        {
                            contentId = contentId.Trim();
                            if (contentId.StartsWith("<"))
                                contentId = contentId.Substring(1);
                            if (contentId.EndsWith(">"))
                                contentId = contentId.Substring(0, contentId.Length - 1);
                            content_id_file.Add(contentId, fileName);
                        }

                        XmlElement part = doc.CreateElement("PART");
                        part.SetAttribute("type", "file");
                        part.SetAttribute("content-id", contentId);
                        part.SetAttribute("filename", fileName);
                        part.SetAttribute("description", e.ContentDescription);
                        if (e.ContentType != null)
                            part.SetAttribute("content-type", e.ContentType.ToString());
                        xml.AppendChild(part);
                    }
                }
                catch (Exception)
                {
                }
            }
            foreach (MIME_Entity e in entities)
            {
                try
                {
                    if (e.Body.MediaType.ToLower() == MIME_MediaTypes.Text.html)
                    {
                        string html = ((MIME_b_Text)e.Body).Text;

                        //处理html中的内嵌图片
                        if (content_id_file.Count > 0)
                        {
                            foreach (string key in content_id_file.Keys)
                            {
                                html = html.Replace("cid:" + key, content_id_file[key]);
                            }
                        }

                        XmlElement part = doc.CreateElement("PART");
                        part.SetAttribute("type", "html");
                        part.AppendChild(doc.CreateCDataSection(html));
                        xml.AppendChild(part);

                        string charset = "GBK";
                        if (e.ContentType != null && e.ContentType.Param_Charset != null)
                            charset = e.ContentType.Param_Charset;
                        else if (m.ContentType != null && m.ContentType.Param_Charset != null)
                            charset = m.ContentType.Param_Charset;

                        string html_charset = getHtmlEncoding(html);
                        if (html_charset == null)
                        {
                            int index = html.IndexOf("<head>", StringComparison.CurrentCultureIgnoreCase);
                            if (index != -1)
                            {
                                StringBuilder sb = new StringBuilder();
                                index = index + "<head>".Length;
                                sb.Append(html.Substring(0, index));
                                sb.Append(@"<meta http-equiv=""content-type"" content=""text/html; charset=").Append(charset).Append(@""">");
                                sb.Append(html.Substring(index));
                                html = sb.ToString();
                            }
                            else
                            {
                                StringBuilder sb = new StringBuilder();
                                sb.Append(@"<html><head><meta http-equiv=""content-type"" content=""text/html; charset=").Append(charset).Append(@""">");
                                sb.Append("</head><body>");
                                sb.Append(html);
                                sb.Append("</body></html>");
                                html = sb.ToString();
                            }
                            html_charset = charset;
                        }

                        Encoding encoding = null;
                        try
                        {
                            encoding = Encoding.GetEncoding(html_charset);
                        }
                        catch (Exception)
                        {
                        }
                        if (encoding == null)
                        {
                            try
                            {
                                encoding = Encoding.GetEncoding(charset);
                            }
                            catch (Exception)
                            {
                            }
                        }
                        if (encoding == null)
                            encoding = Encoding.UTF8;
                        StreamWriter hfs = new StreamWriter(dir + "/" + uid + ".html", false, encoding);
                        hfs.Write(html);
                        hfs.Close();
                    }
                    else if (e.Body.MediaType.ToLower() == MIME_MediaTypes.Text.plain)
                    {
                        XmlElement part = doc.CreateElement("PART");
                        part.SetAttribute("type", "text");
                        string text = ((MIME_b_Text)e.Body).Text;

                        part.AppendChild(doc.CreateCDataSection(text));
                        xml.AppendChild(part);

                        if (hasText)
                            textHtml.Append("<hr/>");
                        hasText = true;
                        text = text.Replace(" ", "&nbsp;");
                        text = text.Replace("\n", "<br/>");
                        textHtml.Append(text);
                    }
                }
                catch (Exception)
                {
                }
            }

            textHtml.Append("</body></html>");
            if (hasText)
            {
                try
                {
                    using (StreamWriter hfs = new StreamWriter(dir + "/" + uid + ".text.html", false, Encoding.UTF8))
                    {
                        hfs.Write(textHtml.ToString());
                    }
                }
                catch (Exception)
                {
                }
            }

            record["attachments"] = attachments.ToString();
            record["contents"] = doc.OuterXml;
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 public MIME_b_MessageRfc822()
     : base(new MIME_h_ContentType("message/rfc822"))
 {
     m_pMessage = new Mail_Message();
 }