/// <summary>
        ///
        /// </summary>
        /// <param name="mail"></param>
        private void GetMailAttachments(ListViewItem lvimail)
        {
            if (retVal == true)
            {
                try
                {
                    message = (POP3_ClientMessage)lvimail.Tag;
                    Mail_Message mime = Mail_Message.ParseFromByte(message.MessageToByte());

                    foreach (MIME_Entity entity in mime.Attachments)
                    {
                        if (entity.ContentDisposition != null && entity.ContentDisposition.Param_FileName != null)
                        {
                            //保存附件中的CSV文件
                            SaveCSV(entity, entity.ContentDisposition.Param_FileName);
                        }
                    }
                }
                catch (Exception x)
                {
                    MessageBox.Show(this, "Error: " + x.Message, "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    retVal = false;
                }
            }
        }
Exemple #2
0
        public List <Mail> ReceiveMail(Setting setting)
        {
            List <Mail> list = new List <Mail>();

            using (POP3_Client pop3_Client = new POP3_Client())
            {
                //设置SMPT服务地址和端口并连接
                pop3_Client.Connect(setting.SmtpHostName, setting.SmtpPort);
                //设置Authentication
                pop3_Client.Auth(new LumiSoft.Net.AUTH.AUTH_SASL_Client_Login(setting.User.UserName, setting.User.Password));
                if (pop3_Client.Messages != null && pop3_Client.Messages.Count > 0)
                {
                    foreach (POP3_ClientMessage message in pop3_Client.Messages)
                    {
                        //将收到的邮件逐一转化Mail实体类型
                        Mail_Message mail_Message = Mail_Message.ParseFromByte(message.MessageToByte());
                        list.Add(new Mail()
                        {
                            From            = mail_Message.From.ToString(),
                            To              = mail_Message.To.ToArray().Select(address => address.ToString()).ToList(),
                            CreatedDateTime = mail_Message.Date,
                            Subject         = mail_Message.Subject,
                            Body            = mail_Message.BodyHtmlText,
                            Attachments     = mail_Message.Attachments.Select(attach => new Attachment(attach.ContentDisposition.Param_FileName)).ToList()
                        });
                    }
                }
            }
            return(list);
        }
Exemple #3
0
 private void DeleteMail(DateTime datetime)
 {
     using (var pop3 = new POP3_Client())
     {
         pop3.Connect(pop3host, 995, true);
         pop3.Timeout = 3000;
         pop3.Login(user, pwd);
         var date = datetime.ToString("yyyy-MM-dd");
         var del  = 0;
         foreach (POP3_ClientMessage m in pop3.Messages)
         {
             var header = Mail_Message.ParseFromByte(m.HeaderToByte());
             var ss     = header.Subject.Split('@');
             if (ss.Length != 2)
             {
                 m.MarkForDeletion();
                 continue;
             }
             if (ss[0] == this.shop && ss[1] == date)
             {
                 m.MarkForDeletion();
                 sb.Append("delete old mail: " + date + "\r\n");
                 del++;
                 continue;
             }
         }
         sb.Append(string.Format("共{0}邮件,删除旧邮件{1}\r\n", pop3.Messages.Count, del));
         pop3.Disconnect();
     }
 }
Exemple #4
0
        private void UpdateData()
        {
            using (var pop3 = new POP3_Client())
            {
                pop3.Connect(this.pop3Host, 995, true);
                pop3.Login(this.user, this.password);
                int delete  = 0;
                int insert  = 0;
                int old     = 0;
                int sum     = pop3.Messages.Count;
                int newShop = 0;
                foreach (POP3_ClientMessage m in pop3.Messages)
                {
                    var header  = Mail_Message.ParseFromByte(m.HeaderToByte());
                    var subject = header.Subject;
                    var ss      = subject.Split('@'); // "wkl@2017-01-01"
                    if (ss.Length != 2)
                    {
                        m.MarkForDeletion();
                        delete++;
                        continue;
                    }
                    if (!shops.Keys.Contains <string>(ss[0]))
                    {
                        newShop++;
                        continue;
                    }
                    DateTime dt;
                    if (!DateTime.TryParse(ss[1], out dt))
                    {
                        m.MarkForDeletion();
                        delete++;
                        continue;
                    }
                    if (this.IsOldUid(m.UID)) //如果已读取过的邮件跳过
                    {
                        if (this.IsOldDate(dt))
                        {
                            m.MarkForDeletion(); //过期删除
                            delete++;
                        }
                        old++;
                        continue;
                    }
                    var mail = Mail_Message.ParseFromByte(m.MessageToByte());
                    var xml  = new XmlDocument();
                    xml.LoadXml(mail.BodyText);
                    this.InsertData(xml, dt);
                    this.InsertOldMail(m.UID, dt);
                    insert++;
                }

                MessageBox.Show(string.Format("共 {0} 条邮件,删除过期邮件 {1}, 略过已读邮件 {2}, 读取新邮件 {3}.\r\n未识别门店邮件 {4}, (如此值大于零, 请添加新门店!)",
                                              sum, delete, old, insert, newShop), "数据处理报告:", MessageBoxButtons.OK, MessageBoxIcon.Information);

                pop3.Disconnect();
            }
        }
Exemple #5
0
 /// <summary>
 /// 获取邮件发送时间
 /// </summary>
 /// <param name="mailIndex"></param>
 /// <returns></returns>
 public override DateTime GetMailSendDate(Int32 mailIndex)
 {
     LumiSoft.Net.Mail.Mail_Message mMessage = Mail_Message.ParseFromByte(_pop3MessageList[mailIndex - 1].HeaderToByte());
     if (mMessage.From != null)
     {
         return(mMessage.Date);
     }
     return(DateTime.MinValue);
 }
Exemple #6
0
 /// <summary>
 /// 获取邮件的主题
 /// </summary>
 /// <param name="mailIndex"></param>
 /// <returns></returns>
 public override String GetMailUid(Int32 mailIndex)
 {
     LumiSoft.Net.Mail.Mail_Message mMessage = Mail_Message.ParseFromByte(_pop3MessageList[mailIndex - 1].HeaderToByte());
     if (mMessage.From != null)
     {
         return(mMessage.Subject);
     }
     return("");
 }
Exemple #7
0
 /// <summary>
 /// 获取邮件正文
 /// </summary>
 /// <param name="mailIndex">邮件顺序</param>
 /// <returns></returns>
 public override String GetMailBodyAsText(Int32 mailIndex)
 {
     LumiSoft.Net.Mail.Mail_Message mMessage = Mail_Message.ParseFromByte(_pop3MessageList[mailIndex - 1].HeaderToByte());
     if (mMessage.From != null)
     {
         return(mMessage.BodyText);
         //return MMessage.BodyHtmlText;
     }
     return("");
 }
        public static List <Email> GetAllEmails(string server, int port, string user, string pwd, bool usessl, bool deleteafterread, ref List <string> errors)
        {
            var ret = new List <Email>();

            errors.Clear();
            var oClient = new POP3_Client();

            try
            {
                oClient.Connect(server, port, usessl);
                oClient.Authenticate(user, pwd, true);
            }
            catch (Exception exception)
            {
                errors.Add("Error connect/authenticate - " + exception.Message);
                return(null);
            }
            foreach (POP3_ClientMessage message in oClient.Messages)
            {
                var wrapper = new Email();
                wrapper.Uid = message.UID;
                try
                {
                    Mail_Message mime = Mail_Message.ParseFromByte(message.HeaderToByte());
                    wrapper.Subject = mime.Subject;
                    wrapper.From    = mime.From[0].Address;
                    wrapper.To      = mime.To[0].ToString();
                    mime            = Mail_Message.ParseFromByte(message.MessageToByte());

                    string sa = mime.BodyHtmlText;
                    if (sa == null)
                    {
                        wrapper.TextBody = mime.BodyText;
                    }
                    else
                    {
                        wrapper.HtmlBody = sa;
                    }
                }
                catch (Exception exception)
                {
                    errors.Add("Error reading " + wrapper.Uid + " - " + exception.Message);
                }
                if (deleteafterread)
                {
                    message.MarkForDeletion();
                }
                ret.Add(wrapper);
            }
            oClient.Disconnect();
            oClient.Dispose();

            return(ret);
        }
Exemple #9
0
    public void TestLumisoftPop3()
    {
        using var client = CreateLumisoftPop3Client();
        var message = client.Messages[0];

        // _testOutputHelper.WriteLine(message.HeaderToString());
        _testOutputHelper.WriteLine(message.UID);

        var bytes       = message.MessageToByte();
        var mailMessage = Mail_Message.ParseFromByte(bytes, Encoding.UTF8);

        _testOutputHelper.WriteLine(mailMessage.MessageID);
    }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string    userId = context.Request.QueryString["UserID"];
            DataTable table;

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM [TU_EmailPOP] WHERE UserID='" + userId + "'", connection);
                table = new DataTable();
                sda.Fill(table);
            }
            string host     = string.Empty;
            string userName = string.Empty;;
            string password = string.Empty;;
            int    port     = 993;
            bool   ssl      = true;

            foreach (DataRow row in table.Rows)
            {
                host     = row["Host"].ToString();
                userName = row["UserName"].ToString();
                password = row["Password"].ToString();
                port     = int.Parse(row["Port"].ToString());
            }
            string      json  = string.Empty;
            List <Item> items = new List <Item>();

            using (POP3_Client client = new POP3_Client())
            {
                client.Connect(host, port, ssl);
                client.Authenticate(userName, password, false);
                var messages = client.Messages;
                foreach (POP3_ClientMessage message in messages)
                {
                    Mail_Message email = Mail_Message.ParseFromByte(message.MessageToByte());
                    Item         item  = new Item
                    {
                        Sender   = email.From.ToString().Replace("\"", ""),
                        Subject  = email.Subject,
                        SendDate = email.Date.ToString(),
                        Date     = email.Date.ToString(),
                    };
                    items.Add(item);
                }
            }
            items = items.OrderByDescending(i => i.SendDate).ToList <Item>();
            json  = JsonConvert.SerializeObject(items);
            context.Response.Write(json);
        }
Exemple #11
0
 public override Boolean GetMailAttachment(Int32 mailIndex, String receiveBackpath)
 {
     if (mailIndex == 0)
     {
         return(false);
     }
     else if (mailIndex > _mailTotalCount)
     {
         return(false);
     }
     else
     {
         try
         {
             byte[]       messageBytes = _pop3MessageList[mailIndex - 1].MessageToByte();
             Mail_Message mMessage     = Mail_Message.ParseFromByte(messageBytes);
             if (mMessage == null)
             {
                 return(false);
             }
             //LumiSoft.Net.Mail.Mail_Message MMessage = Mail_Message.ParseFromByte(pop3MessageList[mailIndex - 1].HeaderToByte());
             foreach (MIME_Entity entity in mMessage.GetAttachments(true, true))
             {
                 if (entity.ContentDisposition != null &&
                     entity.ContentDisposition.Param_FileName != null)
                 {
                     String fileName     = entity.ContentDisposition.Param_FileName;
                     String fileFullName = receiveBackpath + "\\" + fileName;
                     //FileInfo fileInfo = new FileInfo(fileFullName);
                     //if (fileInfo.Exists) fileInfo.Delete();
                     MIME_b_SinglepartBase byteObj = (MIME_b_SinglepartBase)entity.Body;
                     if (byteObj != null)
                     {
                         FileInfo   fileInfo = new FileInfo(fileFullName);
                         FileStream fs       = null; //声明一个文件流对象.
                         fs = new FileStream(fileInfo.FullName, FileMode.Create);
                         fs.Write(byteObj.Data, 0, byteObj.Data.Length);
                         fs.Close();
                         //FileUtil.CreateFile(filePath, byteObj.Data);
                         //fileSize = byteObj.Data.Length;
                         //entity.ContentDisposition.DispositionType == MIME_DispositionTypes.Attachment
                         return(true);
                     }
                 }
             }
             ErrorMessage = "获取附件失败,请重试!";
             return(false);
         }
         catch (Exception ex) { ErrorMessage = ex.Message; return(false); }
     }
 }
Exemple #12
0
            private void Session_Fetch(object sender, IMAP_e_Fetch e)
            {
                foreach (var msgInfo in e.MessagesInfo)
                {
                    var dbMessage = this.messagesRepository.GetMessages().FirstOrDefault(m => m.Id == new Guid(msgInfo.ID));

                    if (dbMessage != null)
                    {
                        ApiModel.Message apiMessage = new ApiModel.Message(dbMessage);
                        Mail_Message     message    = Mail_Message.ParseFromByte(apiMessage.Data);
                        e.AddData(msgInfo, message);
                    }
                }
            }
        public MailMessage FetchNext()
        {
            EnsureConnection();

            if (_popClient.Messages.Count == 0)
            {
                throw new ApplicationException("No messages.");
            }

            var mailMessage = Mail_Message.ParseFromByte(_popClient.Messages[0].MessageToByte());

            _popClient.Messages[0].MarkForDeletion();

            return(new MailMessage(mailMessage.From[0].Address, mailMessage.To.Mailboxes[0].Address, mailMessage.Subject, mailMessage.BodyHtmlText ?? mailMessage.BodyText, GetAttachments(mailMessage.Attachments)));
        }
        public static string SearchSingleEmail(string subject,string date)
        {
            string userId = new WX.WXUser().UserID;
            DataTable table;
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM [TU_EmailPOP] WHERE UserID='" + userId + "'", connection);
                table = new DataTable();
                sda.Fill(table);
            }
            string host = string.Empty;
            string userName = string.Empty;
            string password = string.Empty;
            int port = 995;
            bool ssl = true;
            foreach (DataRow row in table.Rows)
            {
                host = row["Host"].ToString();
                userName = row["UserName"].ToString();
                password = row["Password"].ToString();
                port = int.Parse(row["Port"].ToString());
            }
            string json = string.Empty;
            using (POP3_Client client = new POP3_Client())
            {
                client.Connect(host, port, ssl);
                client.Authenticate(userName, password, false);
                var messages = client.Messages;

                foreach (POP3_ClientMessage message in messages)
                {
                    Mail_Message email = Mail_Message.ParseFromByte(message.MessageToByte());
                    if (email.Subject.Equals(subject) && email.Date == Convert.ToDateTime(date))
                    {
                        TestItem item = new TestItem
                        {
                            Subject = email.Subject,
                            Body = email.BodyHtmlText
                        };
                        json = JsonConvert.SerializeObject(item);
                    }
                }

            }
            return json;
        }
Exemple #15
0
 public void FetchMessages(Action <MailMsgBase> onMessage)
 {
     if (client.Messages.Count > 0)
     {
         var msgs = new List <MailMsgBase>(client.Messages.Count);
         for (int i = client.Messages.Count - 1; i > -1; i--)
         {
             var    pop3Msg = client.Messages[i];
             string uid     = pop3Msg.UID;
             byte[] bytes   = pop3Msg.MessageToByte();
             var    origin  = Mail_Message.ParseFromByte(bytes);
             var    newMsg  = new Pop3Msg(uid, origin);
             msgs.Add(newMsg);
             onMessage?.Invoke(newMsg);
         }
     }
 }
Exemple #16
0
 //Folder will be ingored in pop3 because of not support.
 public List <MailMsgBase> FetchMessages(string folder)
 {
     if (client.Messages.Count > 0)
     {
         var msgs = new List <MailMsgBase>(client.Messages.Count);
         for (int i = client.Messages.Count - 1; i > -1; i--)
         {
             var    pop3Msg = client.Messages[i];
             string uid     = pop3Msg.UID;
             byte[] bytes   = pop3Msg.MessageToByte();
             var    origin  = Mail_Message.ParseFromByte(bytes);
             msgs.Add(new Pop3Msg(uid, origin));
         }
         return(msgs);
     }
     return(null);
 }
Exemple #17
0
 private void GetEmails()
 {
     using (POP3_Client c = new POP3_Client())
     {
         c.Connect("pop.exmail.qq.com", 995, true);
         c.Login("*****@*****.**", "1qaz!QAZ");
         if (c.Messages.Count > 0)
         {
             for (var i = 960; i > -1; i--)
             {
                 //var t = Mail_Message.ParseFromByte(c.Messages[i].MessageTopLinesToByte(50));
                 var header = Mail_Message.ParseFromByte(c.Messages[i].HeaderToByte());
                 var from   = header.From;
                 if (from != null && from.ToArray().Any(a => a.Address == "*****@*****.**"))
                 {
                     var t        = Mail_Message.ParseFromByte(c.Messages[i].MessageToByte());
                     var to       = t.To;
                     var date     = t.Date;
                     var subject  = t.Subject;
                     var bodyText = t.BodyText;
                     try
                     {
                         if (!string.IsNullOrWhiteSpace(t.BodyHtmlText))
                         {
                             bodyText = t.BodyHtmlText;
                         }
                         var match = regx.Match(bodyText);
                         if (this.richText_content.InvokeRequired)
                         {
                             this.richText_content.Invoke(new dispText(() => {
                                 this.richText_content.AppendText("\r\n" + string.Format("Account:{0};Pwd:{1};", match.Groups[1].Value, match.Groups[2].Value));
                             }));
                         }
                         else
                         {
                             this.richText_content.AppendText("\r\n" + string.Format("Account:{1};Pwd:{2};", match.Groups[0].Value, match.Groups[1].Value));
                         }
                     }
                     catch (Exception ex)
                     {}
                 }
             }
         }
     }
 }
Exemple #18
0
        /// <summary>
        /// 获取发件人
        /// </summary>
        /// <param name="mailIndex"></param>
        /// <returns></returns>
        public override String GetSenderName(Int32 mailIndex)
        {
            if (mailIndex == 0)
            {
                return("");
            }
            else if (mailIndex > _mailTotalCount)
            {
                return("");
            }

            LumiSoft.Net.Mail.Mail_Message mMessage = Mail_Message.ParseFromByte(_pop3MessageList[mailIndex - 1].HeaderToByte());
            if (mMessage.From != null)
            {
                return(mMessage.From[0].DisplayName);
            }
            return("");
        }
        /// <summary>
        /// 获取发件人
        /// </summary>
        /// <param name="mailIndex"></param>
        /// <returns></returns>
        public override String GetSendMialAddress(Int32 mailIndex)
        {
            if (mailIndex == 0)
            {
                return("");
            }
            else if (mailIndex > mailTotalCount)
            {
                return("");
            }

            LumiSoft.Net.Mail.Mail_Message MMessage = Mail_Message.ParseFromByte(pop3MessageList[mailIndex - 1].HeaderToByte());
            if (MMessage.From != null)
            {
                return(MMessage.From[0].Address);
            }
            return("");
        }
Exemple #20
0
        private ConcurrentDictionary <string, Mail_Message> GetEmails(string pop3Server, int pop3Port, bool pop3UseSsl, string username, string password)
        {
            List <string> gotEmailIds = new List <string>();
            ConcurrentDictionary <string, Mail_Message> result = new ConcurrentDictionary <string, Mail_Message>();

            using (POP3_Client pop3 = new POP3_Client())
            {
                pop3.Connect(pop3Server, pop3Port, pop3UseSsl);
                pop3.Login(username, password);
                POP3_ClientMessageCollection infos = pop3.Messages;
                int maxRetriveMail = this.GetMaxRetrieveMail();
                int messageCount   = infos != null ? infos.Count : 0;
                int totalEmails    = (maxRetriveMail > 0 && messageCount > maxRetriveMail) ? maxRetriveMail : messageCount;
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Emails from Lotus Notes").Add("MaxRetriveMail", totalEmails).ToInputLogString());

                if (infos != null)
                {
                    for (int i = totalEmails; i > 0; i--)
                    {
                        var info = infos[i - 1];
                        if (gotEmailIds.Contains(info.UID))
                        {
                            continue;
                        }
                        gotEmailIds.Add(info.UID);
                        byte[] messageBytes = info.MessageToByte();

                        if (messageBytes != null && messageBytes.Length > 0)
                        {
                            Mail_Message mimeMessage = Mail_Message.ParseFromByte(messageBytes, new System.Text.UTF8Encoding(false));
                            Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Body").Add("SequenceNumber", i).Add("UID", info.UID).ToOutputLogString());
                            result.TryAdd(info.UID, mimeMessage);
                        }
                        else
                        {
                            Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Body").Add("SequenceNumber", i).Add("Error Message", "Mail Body is null").ToOutputLogString());
                        }
                    }
                }
            }

            return(result);
        }
Exemple #21
0
        private void m_pTabMail_Messages_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try{
                m_pTabMail_MessagesToolbar.Items["save"].Enabled   = false;
                m_pTabMail_MessagesToolbar.Items["delete"].Enabled = false;
                if (m_pTabMail_Messages.SelectedItems.Count > 0)
                {
                    m_pTabMail_Attachments.Items.Clear();
                    m_pTabMail_BodyText.Text = "";

                    POP3_ClientMessage message = (POP3_ClientMessage)m_pTabMail_Messages.SelectedItems[0].Tag;
                    Mail_Message       mime    = Mail_Message.ParseFromByte(message.MessageToByte());

                    foreach (MIME_Entity entity in mime.Attachments)
                    {
                        ListViewItem item = new ListViewItem();
                        if (entity.ContentDisposition != null && entity.ContentDisposition.Param_FileName != null)
                        {
                            item.Text = entity.ContentDisposition.Param_FileName;
                        }
                        else
                        {
                            item.Text = "untitled";
                        }
                        item.Tag = entity;
                        m_pTabMail_Attachments.Items.Add(item);
                    }

                    if (mime.BodyText != null)
                    {
                        m_pTabMail_BodyText.Text = mime.BodyText;
                    }

                    m_pTabMail_MessagesToolbar.Items["save"].Enabled   = true;
                    m_pTabMail_MessagesToolbar.Items["delete"].Enabled = true;
                }
            }
            catch (Exception x) {
                MessageBox.Show(this, "Error: " + x.Message, "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            this.Cursor = Cursors.Default;
        }
Exemple #22
0
            private void Session_Fetch(object sender, IMAP_e_Fetch e)
            {
                using (var scope = this.serviceScopeFactory.CreateScope())
                {
                    var messagesRepository = scope.ServiceProvider.GetService <IMessagesRepository>();

                    foreach (var msgInfo in e.MessagesInfo)
                    {
                        var dbMessage = messagesRepository.GetMessages().SingleOrDefault(m => m.Id == new Guid(msgInfo.ID));

                        if (dbMessage != null)
                        {
                            ApiModel.Message apiMessage = new ApiModel.Message(dbMessage);
                            Mail_Message     message    = Mail_Message.ParseFromByte(apiMessage.Data);
                            e.AddData(msgInfo, message);
                        }
                    }
                }
            }
Exemple #23
0
        public List <Mail_Message> ReciveEmail()
        {
            List <Mail_Message> mailMsgs = new List <Mail_Message>();

            POP3_Client pop3 = new POP3_Client();

            //pop3.Connect("pop3.sina.com.cn",110);
            pop3.Connect(Pop3Server, Pop3Port, SSL);
            //pop3.Login("lulufaer", "ljc123456");
            pop3.Login(MailAccount, MailPassword);

            if (pop3.IsAuthenticated)
            {
                for (int i = 0; i < pop3.Messages.Count; i++)
                {
                    //MailMsg msg= new MailMsg();

                    byte[] bytes = pop3.Messages[i].MessageToByte();

                    Mail_Message m_msg = Mail_Message.ParseFromByte(bytes);

                    //msg.msgFrom = m_msg.From[0].Address;
                    //msg.msgTime = m_msg.Date;
                    //msg.msgTo = m_msg.To.Mailboxes[0].Address;

                    //msg.MsgSubject = m_msg.Subject;
                    //msg.MsgContent = m_msg.BodyText;

                    mailMsgs.Add(m_msg);

                    if (DelAfterRecived)
                    {
                        pop3.Messages[i].MarkForDeletion();
                        //pop3.Messages[i].MarkForDeletion();
                        //pop3.Messages[i].MarkForDeletion();
                    }
                }
            }
            pop3.Disconnect();

            return(mailMsgs);
        }
        /// <summary>
        /// 得到邮件列表
        /// </summary>
        private void GetMailList()
        {
            if (retVal == true)
            {
                try
                {
                    foreach (POP3_ClientMessage msg in pop3.Messages)
                    {
                        Mail_Message mime = Mail_Message.ParseFromByte(msg.HeaderToByte());

                        ListViewItem item = new ListViewItem();
                        if (mime.From != null)
                        {
                            item.Text = mime.From.ToString();
                        }
                        else
                        {
                            item.Text = "<none>";
                        }
                        if (string.IsNullOrEmpty(mime.Subject))
                        {
                            item.SubItems.Add("<none>");
                        }
                        else
                        {
                            item.SubItems.Add(mime.Subject);
                        }
                        item.SubItems.Add(mime.Date.ToString());
                        item.SubItems.Add(((decimal)(msg.Size / (decimal)1000)).ToString("f2") + " kb");
                        item.SubItems.Add(msg.UID);
                        item.Tag = msg;
                        this.listView1.Items.Add(item);
                    }
                }
                catch (Exception x)
                {
                    MessageBox.Show(this, "Error: " + x.Message, "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    retVal = false;
                }
            }
        }
 /// <summary>
 /// 获取
 /// </summary>
 /// <param name="account">配置</param>
 /// <param name="receiveCount">已收邮件数、注意:如果已收邮件数和邮件数量一致则不获取</param>
 /// <returns></returns>
 public static List <MailModel> Get(MailAccount account, int receiveCount)
 {
     try
     {
         var filePath   = DirFileHelper.GetAbsolutePath("~/Resource/EmailFile/");
         var resultList = new List <MailModel>();
         using (POP3_Client pop3Client = new POP3_Client())
         {
             pop3Client.Connect(account.POP3Host, account.POP3Port, account.Ssl);
             pop3Client.Login(account.Account, account.Password);
             var messages = pop3Client.Messages;
             if (receiveCount == messages.Count)
             {
                 return(resultList);
             }
             for (int i = messages.Count - 1; receiveCount <= i; i--)
             {
                 var messageItem   = messages[i];
                 var messageHeader = Mail_Message.ParseFromByte(messageItem.MessageToByte());
                 resultList.Add(new MailModel()
                 {
                     UID        = messageItem.UID,
                     To         = messageHeader.From == null ? "" : messageHeader.From[0].Address,
                     ToName     = messageHeader.From == null ? "" : messageHeader.From[0].DisplayName,
                     Subject    = messageHeader.Subject,
                     BodyText   = messageHeader.BodyHtmlText,
                     Attachment = GetFile(filePath, messageHeader.GetAttachments(true, true), messageItem.UID),
                     Date       = messageHeader.Date,
                 });
             }
         }
         return(resultList);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemple #26
0
        /// <summary>
        /// Gets messages list from POP3 server and adds them to UI.
        /// </summary>
        private void FillMessagesList()
        {
            this.Cursor = Cursors.WaitCursor;
            try{
                foreach (POP3_ClientMessage message in m_pPop3.Messages)
                {
                    Mail_Message mime = Mail_Message.ParseFromByte(message.HeaderToByte());

                    ListViewItem item = new ListViewItem();
                    if (mime.From != null)
                    {
                        item.Text = mime.From.ToString();
                    }
                    else
                    {
                        item.Text = "<none>";
                    }
                    if (string.IsNullOrEmpty(mime.Subject))
                    {
                        item.SubItems.Add("<none>");
                    }
                    else
                    {
                        item.SubItems.Add(mime.Subject);
                    }
                    item.SubItems.Add(mime.Date.ToString());
                    item.SubItems.Add(((decimal)(message.Size / (decimal)1000)).ToString("f2") + " kb");
                    item.Tag = message;
                    m_pTabMail_Messages.Items.Add(item);
                }
            }
            catch (Exception x) {
                MessageBox.Show(this, "Error: " + x.Message, "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            this.Cursor = Cursors.Default;
        }
        /// <summary>
        /// Executes specified actions.
        /// </summary>
        /// <param name="dvActions">Dataview what contains actions to be executed.</param>
        /// <param name="server">Reference to owner virtual server.</param>
        /// <param name="message">Recieved message.</param>
        /// <param name="sender">MAIL FROM: command value.</param>
        /// <param name="to">RCPT TO: commands values.</param>
        public GlobalMessageRuleActionResult DoActions(DataView dvActions, VirtualServer server, Stream message, string sender, string[] to)
        {
            // TODO: get rid of MemoryStream, move to Stream

            //    bool   messageChanged = false;
            bool   deleteMessage = false;
            string storeFolder   = null;
            string errorText     = null;

            // Loop actions
            foreach (DataRowView drV in dvActions)
            {
                GlobalMessageRuleAction_enum action = (GlobalMessageRuleAction_enum)drV["ActionType"];
                byte[] actionData = (byte[])drV["ActionData"];

                // Reset stream position
                message.Position = 0;

                #region AutoResponse

                /* Description: Sends specified autoresponse message to sender.
                 *  Action data structure:
                 *      <ActionData>
                 *          <From></From>
                 *          <Message></Message>
                 *      </ActionData>
                 */

                if (action == GlobalMessageRuleAction_enum.AutoResponse)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    string smtp_from   = table.GetValue("From");
                    string responseMsg = table.GetValue("Message");

                    // See if we have header field X-LS-MailServer-AutoResponse, never answer to auto response.
                    MIME_h_Collection header = new MIME_h_Collection(new MIME_h_Provider());
                    header.Parse(new SmartStream(message, false));
                    if (header.Contains("X-LS-MailServer-AutoResponse"))
                    {
                        // Just skip
                    }
                    else
                    {
                        Mail_Message autoresponseMessage = Mail_Message.ParseFromByte(System.Text.Encoding.Default.GetBytes(responseMsg));

                        // Add header field 'X-LS-MailServer-AutoResponse:'
                        autoresponseMessage.Header.Add(new MIME_h_Unstructured("X-LS-MailServer-AutoResponse", ""));
                        // Update message date
                        autoresponseMessage.Date = DateTime.Now;

                        // Set To: if not explicity set
                        if (autoresponseMessage.To == null || autoresponseMessage.To.Count == 0)
                        {
                            if (autoresponseMessage.To == null)
                            {
                                Mail_t_AddressList t = new Mail_t_AddressList();
                                t.Add(new Mail_t_Mailbox(null, sender));
                                autoresponseMessage.To = t;
                            }
                            else
                            {
                                autoresponseMessage.To.Add(new Mail_t_Mailbox(null, sender));
                            }
                        }
                        // Update Subject: variables, if any
                        if (autoresponseMessage.Subject != null)
                        {
                            if (header.Contains("Subject"))
                            {
                                autoresponseMessage.Subject = autoresponseMessage.Subject.Replace("#SUBJECT", header.GetFirst("Subject").ValueToString().Trim());
                            }
                        }

                        // Sender missing, we can't send auto response.
                        if (string.IsNullOrEmpty(sender))
                        {
                            continue;
                        }

                        server.ProcessAndStoreMessage(smtp_from, new string[] { sender }, new MemoryStream(autoresponseMessage.ToByte(new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8)), null);
                    }
                }

                #endregion

                #region Delete Message

                /* Description: Deletes message.
                 *  Action data structure:
                 *      <ActionData>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.DeleteMessage)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    deleteMessage = true;
                }

                #endregion

                #region ExecuteProgram

                /* Description: Executes specified program.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Program></Program>
                 *          <Arguments></Arguments>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.ExecuteProgram)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    System.Diagnostics.ProcessStartInfo pInfo = new System.Diagnostics.ProcessStartInfo();
                    pInfo.FileName       = table.GetValue("Program");
                    pInfo.Arguments      = table.GetValue("Arguments");
                    pInfo.CreateNoWindow = true;
                    System.Diagnostics.Process.Start(pInfo);
                }

                #endregion

                #region ForwardToEmail

                /* Description: Forwards email to specified email.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Email></Email>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.ForwardToEmail)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    // See If message has X-LS-MailServer-ForwardedTo: and equals to "Email".
                    // If so, then we have cross reference forward, don't forward that message
                    MIME_h_Collection header = new MIME_h_Collection(new MIME_h_Provider());
                    header.Parse(new SmartStream(message, false));
                    bool forwardedAlready = false;
                    if (header.Contains("X-LS-MailServer-ForwardedTo"))
                    {
                        foreach (MIME_h headerField in header["X-LS-MailServer-ForwardedTo"])
                        {
                            if (headerField.ValueToString().Trim() == table.GetValue("Email"))
                            {
                                forwardedAlready = true;
                                break;
                            }
                        }
                    }

                    // Reset stream position
                    message.Position = 0;

                    if (forwardedAlready)
                    {
                        // Just skip
                    }
                    else
                    {
                        // Add header field 'X-LS-MailServer-ForwardedTo:'
                        MemoryStream msFwMessage = new MemoryStream();
                        byte[]       fwField     = System.Text.Encoding.Default.GetBytes("X-LS-MailServer-ForwardedTo: " + table.GetValue("Email") + "\r\n");
                        msFwMessage.Write(fwField, 0, fwField.Length);
                        SCore.StreamCopy(message, msFwMessage);

                        server.ProcessAndStoreMessage(sender, new string[] { table.GetValue("Email") }, msFwMessage, null);
                    }
                }

                #endregion

                #region ForwardToHost

                /* Description: Forwards email to specified host.
                 *              All RCPT TO: recipients are preserved.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Host></Host>
                 *          <Port></Port>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.ForwardToHost)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    foreach (string t in to)
                    {
                        message.Position = 0;
                        server.RelayServer.StoreRelayMessage(
                            Guid.NewGuid().ToString(),
                            null,
                            message,
                            HostEndPoint.Parse(table.GetValue("Host") + ":" + table.GetValue("Port")),
                            sender,
                            t,
                            null,
                            SMTP_DSN_Notify.NotSpecified,
                            SMTP_DSN_Ret.NotSpecified
                            );
                    }
                    message.Position = 0;
                }

                #endregion

                #region StoreToDiskFolder

                /* Description: Stores message to specified disk folder.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Folder></Folder>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.StoreToDiskFolder)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    string folder = table.GetValue("Folder");
                    if (!folder.EndsWith("\\"))
                    {
                        folder += "\\";
                    }

                    if (Directory.Exists(folder))
                    {
                        using (FileStream fs = File.Create(folder + DateTime.Now.ToString("ddMMyyyyHHmmss") + "_" + Guid.NewGuid().ToString().Replace('-', '_').Substring(0, 8) + ".eml")){
                            SCore.StreamCopy(message, fs);
                        }
                    }
                    else
                    {
                        // TODO: log error somewhere
                    }
                }

                #endregion

                #region StoreToIMAPFolder

                /* Description: Stores message to specified IMAP folder.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Folder></Folder>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.StoreToIMAPFolder)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);
                    storeFolder = table.GetValue("Folder");
                }

                #endregion

                #region AddHeaderField

                /* Description: Add specified header field to message main header.
                 *  Action data structure:
                 *      <ActionData>
                 *          <HeaderFieldName></HeaderFieldName>
                 *          <HeaderFieldValue></HeaderFieldValue>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.AddHeaderField)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    Mail_Message mime = Mail_Message.ParseFromStream(message);
                    mime.Header.Add(new MIME_h_Unstructured(table.GetValue("HeaderFieldName"), table.GetValue("HeaderFieldValue")));
                    message.SetLength(0);
                    mime.ToStream(message, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8);

                    //  messageChanged = true;
                }

                #endregion

                #region RemoveHeaderField

                /* Description: Removes specified header field from message mian header.
                 *  Action data structure:
                 *      <ActionData>
                 *          <HeaderFieldName></HeaderFieldName>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.RemoveHeaderField)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    Mail_Message mime = Mail_Message.ParseFromStream(message);
                    mime.Header.RemoveAll(table.GetValue("HeaderFieldName"));
                    message.SetLength(0);
                    mime.ToStream(message, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8);

                    //    messageChanged = true;
                }

                #endregion

                #region SendErrorToClient

                /* Description: Sends error to currently connected client. NOTE: Error text may contain ASCII printable chars only and maximum length is 500.
                 *  Action data structure:
                 *      <ActionData>
                 *          <ErrorText></ErrorText>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.SendErrorToClient)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    errorText = table.GetValue("ErrorText");
                }

                #endregion

                #region StoreToFTPFolder

                /* Description: Stores message to specified FTP server folder.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Server></Server>
                 *          <Port></Server>
                 *          <User></User>
                 *          <Password></Password>
                 *          <Folder></Folder>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.StoreToFTPFolder)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    _MessageRuleAction_FTP_AsyncSend ftpSend = new _MessageRuleAction_FTP_AsyncSend(
                        table.GetValue("Server"),
                        Convert.ToInt32(table.GetValue("Port")),
                        table.GetValue("User"),
                        table.GetValue("Password"),
                        table.GetValue("Folder"),
                        message,
                        DateTime.Now.ToString("ddMMyyyyHHmmss") + "_" + Guid.NewGuid().ToString().Replace('-', '_').Substring(0, 8) + ".eml"
                        );
                }

                #endregion

                #region PostToNNTPNewsGroup

                /* Description: Posts message to specified NNTP newsgroup.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Server></Server>
                 *          <Port></Server>
                 *          <User></User>
                 *          <Password></Password>
                 *          <Newsgroup></Newsgroup>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.PostToNNTPNewsGroup)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    // Add header field "Newsgroups: newsgroup", NNTP server demands it.
                    Mail_Message mime = Mail_Message.ParseFromStream(message);
                    if (!mime.Header.Contains("Newsgroups:"))
                    {
                        mime.Header.Add(new MIME_h_Unstructured("Newsgroups:", table.GetValue("Newsgroup")));
                    }

                    _MessageRuleAction_NNTP_Async nntp = new _MessageRuleAction_NNTP_Async(
                        table.GetValue("Server"),
                        Convert.ToInt32(table.GetValue("Port")),
                        table.GetValue("Newsgroup"),
                        new MemoryStream(mime.ToByte(new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8))
                        );
                }

                #endregion

                #region PostToHTTP

                /* Description: Posts message to specified page via HTTP.
                 *  Action data structure:
                 *      <ActionData>
                 *          <URL></URL>
                 *          <FileName></FileName>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.PostToHTTP)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    _MessageRuleAction_HTTP_Async http = new _MessageRuleAction_HTTP_Async(
                        table.GetValue("URL"),
                        message
                        );
                }

                #endregion
            }

            return(new GlobalMessageRuleActionResult(deleteMessage, storeFolder, errorText));
        }
Exemple #28
0
        /// <summary>
        /// Reads the mail.
        /// </summary>
        public MailboxReaderResult ReadMail()
        {
            var             result   = new MailboxReaderResult();
            IList <Project> projects = new List <Project>();

            LogInfo("MailboxReader: Begin read mail.");

            try
            {
                using (var pop3Client = new POP3_Client())
                {
                    // configure the logger
                    pop3Client.Logger           = new Logger();
                    pop3Client.Logger.WriteLog += LogPop3Client;

                    // connect to the server
                    pop3Client.Connect(Config.Server, Config.Port, Config.UseSsl);

                    // authenticate
                    pop3Client.Login(Config.Username, Config.Password);

                    // process the messages on the server
                    foreach (POP3_ClientMessage message in pop3Client.Messages)
                    {
                        var mailHeader = Mail_Message.ParseFromByte(message.HeaderToByte());

                        if (mailHeader != null)
                        {
                            var messageFrom = string.Empty;

                            if (mailHeader.From.Count > 0)
                            {
                                messageFrom = string.Join("; ", mailHeader.From.ToList().Select(p => p.Address).ToArray()).Trim();
                            }

                            var recipients = mailHeader.To.Mailboxes.Select(mailbox => mailbox.Address).ToList();

                            if (mailHeader.Cc != null)
                            {
                                recipients.AddRange(mailHeader.Cc.Mailboxes.Select(mailbox => mailbox.Address));
                            }

                            if (mailHeader.Bcc != null)
                            {
                                recipients.AddRange(mailHeader.Bcc.Mailboxes.Select(mailbox => mailbox.Address));
                            }

                            // loop through the mailboxes
                            foreach (var address in recipients)
                            {
                                var pmbox = ProjectMailboxManager.GetByMailbox(address);

                                // cannot find the mailbox skip the rest
                                if (pmbox == null)
                                {
                                    LogWarning(string.Format("MailboxReader: could not find project mailbox: {0} skipping.", address));
                                    continue;
                                }

                                var project = projects.FirstOrDefault(p => p.Id == pmbox.ProjectId);

                                if (project == null)
                                {
                                    project = ProjectManager.GetById(pmbox.ProjectId);

                                    // project is disabled skip
                                    if (project.Disabled)
                                    {
                                        LogWarning(string.Format("MailboxReader: Project {0} - {1} is flagged as disabled skipping.", project.Id, project.Code));
                                        continue;
                                    }

                                    projects.Add(project);
                                }

                                var entry = new MailboxEntry
                                {
                                    Title          = mailHeader.Subject.Trim(),
                                    From           = messageFrom,
                                    ProjectMailbox = pmbox,
                                    Date           = mailHeader.Date,
                                    Project        = project,
                                    Content        = "Email Body could not be parsed."
                                };

                                var mailbody = Mail_Message.ParseFromByte(message.MessageToByte());

                                if (string.IsNullOrEmpty(mailbody.BodyHtmlText)) // no html must be text
                                {
                                    entry.Content = mailbody.BodyText.Replace("\n\r", "<br/>").Replace("\r\n", "<br/>").Replace("\r", "");
                                }
                                else
                                {
                                    //TODO: Enhancements could include regular expressions / string matching or not matching
                                    // for particular strings values in the subject or body.
                                    // strip the <body> out of the message (using code from below)
                                    var bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                    var match         = bodyExtractor.Match(mailbody.BodyHtmlText);

                                    var emailContent = match.Success && match.Groups["content"] != null
                                        ? match.Groups["content"].Value
                                        : mailbody.BodyHtmlText;

                                    entry.Content = emailContent.Replace("&lt;", "<").Replace("&gt;", ">");
                                    entry.IsHtml  = true;
                                }

                                if (Config.ProcessAttachments && project.AllowAttachments)
                                {
                                    foreach (var attachment in mailbody.GetAttachments(Config.ProcessInlineAttachedPictures).Where(p => p.ContentType != null))
                                    {
                                        entry.MailAttachments.Add(attachment);
                                    }
                                }

                                //save this message
                                SaveMailboxEntry(entry);

                                // add the entry if the save did not throw any exceptions
                                result.MailboxEntries.Add(entry);

                                LogInfo(string.Format(
                                            "MailboxReader: Message #{0} processing finished, found [{1}] attachments, total saved [{2}].",
                                            message.SequenceNumber,
                                            entry.MailAttachments.Count, entry.AttachmentsSavedCount));

                                // delete the message?.
                                if (!Config.DeleteAllMessages)
                                {
                                    continue;
                                }

                                try
                                {
                                    message.MarkForDeletion();
                                }
                                catch (Exception)
                                {
                                }
                            }
                        }
                        else
                        {
                            LogWarning(string.Format("pop3Client: Message #{0} header could not be parsed.", message.SequenceNumber));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
                result.LastException = ex;
                result.Status        = ResultStatuses.FailedWithException;
            }

            LogInfo("MailboxReader: End read mail.");

            return(result);
        }
Exemple #29
0
        public void LoadMessages(String start, String end)
        {
            if (!_IsConnected)
            {
                throw new EMailException {
                          ExceptionType = EMAIL_EXCEPTION_TYPE.NOT_CONNECTED
                }
            }
            ;

            int intStart = 0;

            int.TryParse(start, out intStart);
            int intEnd = Client.Messages.Count - 1;

            int.TryParse(end, out intEnd);

            int okEnd   = (intEnd > Client.Messages.Count - 1 || intEnd < 1) ? Client.Messages.Count - 1 : intEnd;
            int okStart = (intStart <0 || intStart> okEnd) ? 0 : intStart;

            for (int i = okStart; i <= okEnd; i++)
            {
                POP3_ClientMessage   item = Client.Messages[i];
                POP3_Message_Wrapper wr   = new POP3_Message_Wrapper();
                Mail_Message         mime = Mail_Message.ParseFromByte(item.MessageToByte());

                string             body = mime.BodyText;
                Mail_t_AddressList cc   = mime.Cc;
                MIME_Entity[]      atts = mime.Attachments;
                Mail_t_AddressList to   = mime.To;

                wr.Date = mime.Date;
                foreach (var fr in mime.From)
                {
                    if (fr is Mail_t_Mailbox)
                    {
                        wr.From.Add(((Mail_t_Mailbox)fr).Address);
                    }
                }
                wr.UID            = mime.MessageID;
                wr.SequenceNumber = item.SequenceNumber;
                wr.Subject        = mime.Subject;
                wr.TextBody       = String.IsNullOrWhiteSpace(mime.BodyText) ? mime.BodyHtmlText : mime.BodyText;

                foreach (MIME_Entity entity in mime.Attachments)
                {
                    POP3_Mail_Attachment att = new POP3_Mail_Attachment();
                    if (entity.ContentDisposition != null && entity.ContentDisposition.Param_FileName != null)
                    {
                        att.Text = entity.ContentDisposition.Param_FileName;
                    }
                    else
                    {
                        att.Text = "untitled";
                    }
                    att.Body = ((MIME_b_SinglepartBase)entity.Body).Data;
                    wr.Attachments.Add(att);
                }
                _Messages.Add(wr);
            }
        }
Exemple #30
0
        public void functionPOP()
        {
            using (POP3_Client c = new POP3_Client())
            {
                try
                {
                    //连接POP3服务器
                    c.Connect("outlook.office365.com", 995, true);
                    //验证用户身份
                    c.Login(UserName, Pwd);  //邮件密码/smtp、pop3授权码
                    MessageBox.Show("数量:" + c.Messages.Count.ToString());
                    if (c.Messages.Count > 0)
                    {
                        //遍历收件箱里的每一封邮件
                        var message = c.Messages[0];
                        //foreach (POP3_ClientMessage message in c.Messages)
                        //{
                        //try
                        //{
                        //mail.MarkForDeletion(); //删除邮件

                        //收件人、发件人、主题、时间等等走在mime_header里获得
                        Mail_Message mime_header = Mail_Message.ParseFromByte(message.HeaderToByte());

                        //发件人
                        if (mime_header.From != null)
                        {
                            string displayname = mime_header.From[0].DisplayName;
                            string from        = mime_header.From[0].Address;
                            MessageBox.Show($"displayname:{displayname}--from{from}");
                        }

                        //收件人
                        if (mime_header.To != null)
                        {
                            StringBuilder sb = new StringBuilder();
                            foreach (Mail_t_Mailbox recipient in mime_header.To.Mailboxes)
                            {
                                string displayname = recipient.DisplayName;
                                string address     = recipient.Address;
                                if (!string.IsNullOrEmpty(displayname))
                                {
                                    sb.AppendFormat("{0}({1});", displayname, address);
                                }
                                else
                                {
                                    sb.AppendFormat("{0};", address);
                                }
                            }
                        }

                        //抄送
                        if (mime_header.Cc != null)
                        {
                            StringBuilder sb = new StringBuilder();
                            foreach (Mail_t_Mailbox recipient in mime_header.Cc.Mailboxes)
                            {
                                string displayname = recipient.DisplayName;
                                string address     = recipient.Address;
                                if (!string.IsNullOrEmpty(displayname))
                                {
                                    sb.AppendFormat("{0}({1});", displayname, address);
                                }
                                else
                                {
                                    sb.AppendFormat("{0};", address);
                                }
                            }
                        }

                        //发送邮件时间
                        DateTime dateTime     = mime_header.Date;
                        string   ContentID    = mime_header.ContentID;
                        string   MessageID    = mime_header.MessageID;
                        string   OrgMessageID = mime_header.OriginalMessageID;
                        string   Subject      = mime_header.Subject;

                        byte[] messageBytes = message.MessageToByte();

                        Mail_Message mime_message = Mail_Message.ParseFromByte(messageBytes);
                        if (mime_message == null)
                        {
                            //continue;
                            return;
                        }
                        string Body = mime_message.BodyText;
                        //try
                        //{
                        if (!string.IsNullOrEmpty(mime_message.BodyHtmlText))
                        {
                            //邮件内容
                            string BodyHtml = mime_message.BodyHtmlText;
                            //MessageBox.Show(BodyHtml);
                        }
                        //}
                        //catch
                        //{

                        //}
                        //}
                        //catch (Exception ex)
                        //{

                        //}
                    }
                    //}
                    //}
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }