Beispiel #1
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); }
     }
 }
Beispiel #2
0
        private CommunicationPoolEntity GetMailContent(Mail_Message message, int messageNumber)
        {
            CommunicationPoolEntity mail = null;

            if (message != null)
            {
                string displayName   = message.From != null ? message.From[0].DisplayName.NullSafeTrim() : "-";
                string senderAddress = message.From != null ? message.From[0].Address.NullSafeTrim() : "-";
                string senderName    = !string.IsNullOrWhiteSpace(displayName) ? displayName : ApplicationHelpers.GetSenderAddress(senderAddress);
                string recvDate      = message.Date == DateTime.MinValue ? "date not specified" : message.Date.FormatDateTime(Constants.DateTimeFormat.DefaultFullDateTime);

                Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Content").Add("Subject", message.Subject).Add("From", senderAddress)
                            .Add("SenderName", senderName).Add("MessageId", message.MessageID).Add("MessageNumber", messageNumber)
                            .Add("RecvDateTime", recvDate).ToInputLogString());

                mail = new CommunicationPoolEntity();
                mail.SenderAddress = senderAddress;
                mail.SenderName    = senderName;
                mail.Subject       = ApplicationHelpers.StringLimit(message.Subject.RemoveExtraSpaces(), Constants.MaxLength.MailSubject);
                mail.Content       = ApplicationHelpers.StripHtmlTags(GetMailMessage(message));
                mail.PlainText     = ApplicationHelpers.RemoveHtmlTags(GetMailMessage(message).ReplaceBreaks());
                mail.MessageNumber = messageNumber;
                mail.RecvDateTime  = message.Date;

                MIME_Entity[] list = message.GetAttachments(true, true);

                if (list != null && list.Length > 0)
                {
                    Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Attachments").Add("ListSize", list.Length).ToOutputLogString());

                    foreach (MIME_Entity entity in list)
                    {
                        try
                        {
                            if (entity != null)
                            {
                                string fileName;
                                string dispoType;
                                string contentId   = entity.ContentID.ExtractContentID();
                                string contentType = entity.ContentType.TypeWithSubtype.ToLowerInvariant();

                                if (entity.ContentDisposition != null)
                                {
                                    fileName  = entity.ContentDisposition.Param_FileName;
                                    dispoType = entity.ContentDisposition.DispositionType;

                                    // Retrieve file name from contentType instead.
                                    if (string.IsNullOrWhiteSpace(fileName))
                                    {
                                        fileName = entity.ContentType.Param_Name;
                                    }

                                    Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Attachment").Add("ContentDisposition", "NOT NULL").Add("ContentId", contentId)
                                                .Add("FileName", fileName).Add("ContentType", contentType).Add("DispositionType", dispoType).ToInputLogString());

                                    if (entity.Body != null && entity.Body is MIME_b_SinglepartBase)
                                    {
                                        Logger.Info(_logMsg.Clear().SetPrefixMsg("Download Attachment").ToInputLogString());
                                        byte[] bytes = ((MIME_b_SinglepartBase)entity.Body).Data;

                                        if (bytes != null && bytes.Length > 0)
                                        {
                                            if ((string.IsNullOrWhiteSpace(contentId) || MIME_DispositionTypes.Attachment.Equals(dispoType)) && !string.IsNullOrWhiteSpace(fileName))
                                            {
                                                var attachment = new AttachmentEntity();
                                                attachment.ContentType = contentType;
                                                attachment.ByteArray   = bytes;
                                                attachment.Filename    = fileName;
                                                mail.Attachments.Add(attachment);
                                            }
                                            if (!string.IsNullOrWhiteSpace(contentId) && MIME_DispositionTypes.Inline.Equals(dispoType) && contentType.IsImage())
                                            {
                                                // data:image/png;base64,{0}
                                                string base64String = ApplicationHelpers.GetBase64Image(bytes);
                                                string newImg       = string.Format(CultureInfo.InvariantCulture, "data:{0};base64,{1}", contentType, base64String);
                                                string srcImg       = string.Format(CultureInfo.InvariantCulture, "cid:{0}", contentId);
                                                mail.Content = mail.Content.Replace(srcImg, newImg);
                                                Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Attachment").Add("NewImg", newImg).Add("SrcImg", srcImg).ToOutputLogString());
                                            }
                                        }

                                        Logger.Info(_logMsg.Clear().SetPrefixMsg("Download Attachment").ToSuccessLogString());
                                    }
                                }
                                else
                                {
                                    Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Attachment").Add("ContentDisposition", "NULL").Add("ContentId", contentId)
                                                .Add("ContentType", contentType).ToInputLogString());

                                    if (entity.Body != null && entity.Body is MIME_b_SinglepartBase)
                                    {
                                        Logger.Info(_logMsg.Clear().SetPrefixMsg("Download Attachment").ToInputLogString());
                                        byte[] bytes = ((MIME_b_SinglepartBase)entity.Body).Data;

                                        if (bytes != null && bytes.Length > 0)
                                        {
                                            if (!string.IsNullOrWhiteSpace(contentId) && contentType.IsImage())
                                            {
                                                // data:image/png;base64,{0}
                                                string base64String = ApplicationHelpers.GetBase64Image(bytes);
                                                string newImg       = string.Format(CultureInfo.InvariantCulture, "data:{0};base64,{1}", contentType, base64String);
                                                string srcImg       = string.Format(CultureInfo.InvariantCulture, "cid:{0}", contentId);
                                                mail.Content = mail.Content.Replace(srcImg, newImg);
                                                Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Attachment").Add("NewImg", newImg).Add("SrcImg", srcImg).ToOutputLogString());
                                            }
                                        }
                                        Logger.Info(_logMsg.Clear().SetPrefixMsg("Download Attachment").ToSuccessLogString());
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            mail.IsDeleted = false;
                            Logger.Error("Exception occur:\n", ex);
                            Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Content").Add("Error Message", ex.Message).ToFailLogString());
                        }
                    }
                }
                else
                {
                    Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Attachments").Add("ListSize", "0").ToOutputLogString());
                }

                Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Content").Add("Content", mail.Content).ToSuccessLogString());
            }
            else
            {
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Content").Add("Error Message", "Mail Content is null").ToFailLogString());
            }

            return(mail);
        }
        public static void ConvertToMailMessage(this MailMessage msg, POP3_ClientMessage message)
        {
            Mail_Message mime_header = Mail_Message.ParseFromByte(message.HeaderToByte());

            if (mime_header.From != null)
            {
                msg.From = new MailAddress(mime_header.From[0].Address, mime_header.From[0].DisplayName, Encoding.UTF8);;
            }
            if (mime_header.To != null)
            {
                foreach (Mail_t_Mailbox recipient in mime_header.To.Mailboxes)
                {
                    msg.To.Add(new MailAddress(recipient.Address, recipient.DisplayName, Encoding.UTF8));
                }
            }
            if (mime_header.Cc != null)
            {
                foreach (Mail_t_Mailbox recipient in mime_header.Cc.Mailboxes)
                {
                    msg.CC.Add(new MailAddress(recipient.Address, recipient.DisplayName, Encoding.UTF8));
                }
            }
            msg.Subject = mime_header.Subject;
            Mail_Message mime_message = Mail_Message.ParseFromByte(message.MessageToByte());

            if (mime_message == null)
            {
                return;
            }
            msg.Body = mime_message.BodyText;
            //info.Body = mime_message.BodyText;
            try
            {
                if (!string.IsNullOrEmpty(mime_message.BodyHtmlText))
                {
                    msg.Body = mime_message.BodyHtmlText;
                }
            }
            catch
            {
                //屏蔽编码出现错误的问题,错误在BodyText存在而BodyHtmlText不存在的时候,访问BodyHtmlText会出现
            }
            #region 邮件附件内容
            foreach (MIME_Entity entity in mime_message.GetAttachments(true, true))
            {
                if (entity.ContentDisposition != null && entity.ContentDisposition.Param_FileName != null)
                {
                    if (entity.ContentDisposition.DispositionType == MIME_DispositionTypes.Attachment)
                    {
                        string fileName = entity.ContentDisposition.Param_FileName;
                        MIME_b_SinglepartBase byteObj = (MIME_b_SinglepartBase)entity.Body;
                        if (byteObj != null)
                        {
                            //可将字节保存到文件
                            int fileSize = byteObj.Data.Length;
                        }
                        //msg.Attachments.Add(new Attachment(fileName, System.Net.Mime.MediaTypeNames.Application.Rtf));
                    }
                }
            }
            #endregion 邮件附件内容
        }
Beispiel #4
0
        private void ReceiveMail(string OApop3Server, Int32 OApop3ServerPort, string OAUsername, string OAUserPwd, string OutPath, string EmailSubject, string EmailAddress)
        {
            using (POP3_Client pop3 = new POP3_Client())
            {
                try {
                    pop3.Connect(OApop3Server, OApop3ServerPort, true);
                }
                catch (Exception ex) { }
                pop3.Connect(OApop3Server, OApop3ServerPort, true);
                pop3.Login(OAUsername, OAUserPwd);//两个参数,前者为Email的账号,后者为Email的密码

                POP3_ClientMessageCollection messages = pop3.Messages;

                LogHelper.WriteLog(LogLevel.LOG_LEVEL_INFO, string.Format("共{0}封邮件", messages.Count), typeof(AMSDownloadForm));

                for (int i = 0; i < messages.Count; i++)
                {
                    POP3_ClientMessage message = messages[i];//转化为POP3
                    LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("正在检查第{0}封邮件...", i + 1), typeof(AMSDownloadForm));
                    if (message != null)
                    {
                        byte[] messageBytes = null;
                        try {
                            messageBytes = message.MessageToByte();
                        }
                        catch (Exception ex) {
                            LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, string.Format("第{0}封邮件,message.MessageToByte() 失败 错误日志参考下一条信息", i), typeof(AMSDownloadForm));
                            LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(AMSDownloadForm));
                        }
                        Mail_Message mime_message = Mail_Message.ParseFromByte(messageBytes);

                        string sender        = mime_message.From == null ? "sender is null" : mime_message.From[0].DisplayName;
                        string senderAddress = mime_message.From == null ? "senderAddress is null" : mime_message.From[0].Address;
                        string subject       = mime_message.Subject ?? "subject is null";
                        string recDate       = mime_message.Date == DateTime.MinValue ? "date not specified" : mime_message.Date.ToString();
                        string content       = mime_message.BodyText ?? "content is null";

                        LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("正在检查第{0}封邮件, 邮件发送时间{1}", i + 1, mime_message.Date), typeof(AMSDownloadForm));
                        //Console.WriteLine("内容为{0}", content);

                        // 判断此邮件是否是需要下载的邮件
                        // 发件人 & 发件主体 && 收件时间
                        DateTime dt = DateTime.Now;
                        if (string.Equals(senderAddress, EmailAddress) && string.Equals(subject, EmailSubject.Replace("yyyyMMdd", dt.ToString("yyyyMMdd"))) && mime_message.Date.Date == dt.Date)
                        {
                            MIME_Entity[] attachments = mime_message.GetAttachments(true, true);

                            foreach (MIME_Entity entity in attachments)
                            {
                                if (entity.ContentDisposition != null)
                                {
                                    string fileName = entity.ContentDisposition.Param_FileName;
                                    if (!string.IsNullOrEmpty(fileName))
                                    {
                                        DirectoryInfo dir = new DirectoryInfo(OutPath);
                                        if (!dir.Exists)
                                        {
                                            dir.Create();
                                        }
                                        DirectoryInfo dir2 = new DirectoryInfo(OutPath + @"\" + DateTime.Now.ToString("yyyyMMdd") + @"\");
                                        if (!dir2.Exists)
                                        {
                                            dir2.Create();
                                        }

                                        string path = Path.Combine(dir.FullName, fileName);
                                        MIME_b_SinglepartBase byteObj = (MIME_b_SinglepartBase)entity.Body;
                                        Stream decodedDataStream      = byteObj.GetDataStream();
                                        using (FileStream fs = new FileStream(path, FileMode.Create))
                                        {
                                            LumiSoft.Net.Net_Utils.StreamCopy(decodedDataStream, fs, 4000);
                                        }

                                        LogHelper.WriteLog(LogLevel.LOG_LEVEL_INFO, string.Format("{0}已经被下载。", fileName), typeof(AMSDownloadForm));

                                        // 下载完成之后解压
                                        (new FastZip()).ExtractZip(dir.FullName + fileName, dir2.FullName, "");

                                        if (dir2.GetFiles().Length > 0 && dir2.GetDirectories().Length > 0)
                                        {
                                            MessageDxUtil.ShowTips("下载解压文件成功");
                                        }
                                    }
                                }
                            }

                            if (MessageDxUtil.ShowTips("下载成功") == DialogResult.OK)
                            {
                                Process.Start("explorer.exe", OutPath);
                            }

                            break;
                        }

                        // 时间超过了也退出
                        if (mime_message.Date.Date < dt.Date)
                        {
                            MessageDxUtil.ShowTips("根网清算文件未到,请稍后处理");
                            break;
                        }
                    }
                }
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_INFO, "执行结束", typeof(AMSDownloadForm));
            }
        }
        private void button10_Click(object sender, EventArgs e)
        {
            POPserver = textBox8.Text;
            user      = textBox9.Text;
            password  = textBox6.Text;

            TcpClient receiver = new TcpClient();

            try
            {
                receiver.Connect(POPserver, 110);
                liststatus.Items.Add("连接成功");
            }
            catch
            {
                MessageBox.Show("无法连接到服务器");
            }

            nwStream = receiver.GetStream();
            if (nwStream == null)
            {
                throw new Exception("无法取得回复");
            }
            string returnMsg = ReadStream(ref nwStream);

            checkerror(returnMsg);
            liststatus.Items.Add("连接应答" + returnMsg + "\r\n");

            try
            {
                WriteStream(ref nwStream, "USER " + user);
                returnMsg = ReadStream(ref nwStream);
                checkerror(returnMsg);
                liststatus.Items.Add("POP3server:" + returnMsg + "\r\n");
                WriteStream(ref nwStream, "PASS " + password);
                returnMsg = ReadStream(ref nwStream);
                checkerror(returnMsg);
                liststatus.Items.Add("POP3server:" + returnMsg + "\r\n");
                WriteStream(ref nwStream, "STAT");
                returnMsg = ReadStream(ref nwStream);
                checkerror(returnMsg);
                liststatus.Items.Add("POP3server:" + returnMsg + "\r\n");
                string[] totalstat = returnMsg.Split(new char[] { ' ' });
                mailnumber     = Int32.Parse(totalstat[1]);
                textBox10.Text = "共" + totalstat[1] + "封邮件";
                //接收邮件
                POP3_Client pop = new POP3_Client();
                pop.Connect(POPserver, 995, true);
                liststatus.Items.Add("连接成功");
                pop.Login(user, password);
                POP3_ClientMessageCollection messages = pop.Messages;


                for (int i = 0; i < mailnumber; i++)
                {
                    POP3_ClientMessage message = messages[i];
                    if (message != null)
                    {
                        Byte[]       messageBytes = message.MessageToByte();
                        Mail_Message mimemessage  = Mail_Message.ParseFromByte(messageBytes);
                        pop3client   cli          = new pop3client(mimemessage.From[0].DisplayName, mimemessage.From[0].Address, mimemessage.Date.ToLongDateString(),
                                                                   mimemessage.Subject, mimemessage.BodyText, mimemessage.GetAttachments(true, true), i + 1);
                        mailreceive.Add(cli);
                        // mailreceive[i].sender1= mimemessage.From[0].DisplayName;
                        //mailreceive[i].senderaddress = mimemessage.From[0].Address;
                        //mailreceive[i].senderdate = mimemessage.Date.ToLongDateString();
                        // mailreceive[i].subject = mimemessage.Subject;
                        //mailreceive[i].content = mimemessage.BodyText;
                        //mailreceive[i].attachment = mimemessage.GetAttachments(true, true);
                        //mailreceive[i].num = i + 1;
                        listView1.Items.Add(new ListViewItem(new string[] { (i + 1).ToString(), mailreceive[i].sender1, mailreceive[i].subject, mailreceive[i].senderdate, "无" }));
                        foreach (MIME_Entity entity in mailreceive[i].attachment)
                        {
                            string filename = entity.ContentDisposition.Param_FileName;
                            cli.getfilename(filename);
                            listView1.Items[i].SubItems.Add(" ");
                            listView1.Items[i].SubItems[4].Text = filename;
                        }
                    }
                }
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine("登陆失败");
            }
        }
Beispiel #6
0
        private string GetMessageContent(Mail_Message mailbody, Project project, out bool isContentHtml, ref List <MIME_Entity> attachments)
        {
            string content = "";

            isContentHtml = false;
            attachments   = new List <MIME_Entity>();

            // parse the text content
            if (string.IsNullOrEmpty(mailbody.BodyHtmlText)) // no html must be text
            {
                content = mailbody.BodyText.Replace("\n\r", "<br/>").Replace("\r\n", "<br/>").Replace("\r", "");
                int replyToPos = content.IndexOf("-- WRITE ABOVE THIS LINE TO REPLY --");
                if (replyToPos != -1)
                {
                    content = content.Substring(0, replyToPos);
                }
            }
            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;

                isContentHtml = true;
                content       = emailContent.Replace("&lt;", "<").Replace("&gt;", ">");

                content = Regex.Replace(content, "</?o:p>", string.Empty); // Clean MSWord stuff

                int replyToStart = content.IndexOf("<p>-- WRITE ABOVE THIS LINE TO REPLY --</p>");
                int replyToEnd   = content.IndexOf("<p>-- WRITE BELOW THIS LINE TO REPLY --</p>");
                if (replyToStart != -1 && replyToEnd != -1)
                {
                    content = content.Substring(0, replyToStart) +
                              content.Substring(replyToEnd + 43);
                }
            }

            // parse attachments
            if (Config.ProcessAttachments && project.AllowAttachments)
            {
                List <MIME_Entity> allAttachs = mailbody.GetAttachments(Config.ProcessInlineAttachedPictures).Where(p => p.ContentType != null).ToList();

                // parse inline images
                for (int i = 0; i < allAttachs.Count; i++)
                {
                    var attachment = allAttachs[i];
                    if (attachment.Body is MIME_b_Image && !string.IsNullOrEmpty(attachment.ContentID))
                    {
                        var inlineKey = "cid:" + attachment.ContentID.Replace("<", "").Replace(">", "");
                        if (content.Contains(inlineKey))
                        {
                            content = content.Replace(inlineKey, ConvertImageToBase64(attachment));
                        }
                        else
                        {
                            attachments.Add(attachment);
                        }
                    }
                    else
                    {
                        attachments.Add(attachment);
                    }
                }
            }

            return(content);
        }