private void m_pTabMail_MessagesToolbar_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { this.Cursor = Cursors.WaitCursor; try{ if (string.Equals(e.ClickedItem.Name, "save")) { SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = "message.eml"; if (dlg.ShowDialog() == DialogResult.OK) { this.Cursor = Cursors.WaitCursor; POP3_ClientMessage message = (POP3_ClientMessage)m_pTabMail_Messages.SelectedItems[0].Tag; File.WriteAllBytes(dlg.FileName, message.MessageToByte()); this.Cursor = Cursors.Default; } } else if (string.Equals(e.ClickedItem.Name, "delete")) { if (MessageBox.Show(this, "Do you want to delete selected message ?", "Confirm Delete:", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { POP3_ClientMessage message = (POP3_ClientMessage)m_pTabMail_Messages.SelectedItems[0].Tag; message.MarkForDeletion(); m_pTabMail_Messages.SelectedItems[0].Remove(); } } } catch (Exception x) { MessageBox.Show(this, "Error: " + x.Message, "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error); } this.Cursor = Cursors.Default; }
private void SaveEmail(POP3_ClientMessage message) { var msg = new MailMessage(); msg.ConvertToMailMessage(message); LogHelper.Info(string.Format("From:\"{0}\"{1}", msg.From.Address, msg.From.DisplayName)); string tos = ""; foreach (var to in msg.To) { tos += string.Format("\"{0}\"{1};", to.Address, to.DisplayName); } LogHelper.Info(string.Format("To:{0}", tos)); string ccs = ""; foreach (var cc in msg.CC) { ccs += string.Format("\"{0}\"{1};", cc.Address, cc.DisplayName); } LogHelper.Info(string.Format("CC:{0}", ccs)); LogHelper.Info("Subject" + msg.Subject); //LogHelper.Info("Body:" + msg.Body); //msg.ToArray(); //MailWriter }
/// <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; } } }
private void SaveEmail(POP3_ClientMessage message) { var msg = new MailMessage(); msg.ConvertToMailMessage(message); LogHelper.Info(msg.From); LogHelper.Info(msg.To); LogHelper.Info(msg.CC); LogHelper.Info(msg.Body); LogHelper.Info(msg.Subject); msg.ToArray(); //MailWriter }
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; }
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); } }
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 邮件附件内容 }
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 LumiSoftMail() { string sendmail, HtmlBody = "", date; //网络连接判断 if (!IsNetConnect()) { return; } POP3_Client popMail = new POP3_Client(); try { popMail.Timeout = HtmlTextPath.EMAIL_TIME_OUT; if (string.IsNullOrEmpty(MAIL_USER_NAME) || string.IsNullOrEmpty(MAIL_USER_PWD) || string.IsNullOrEmpty(MAIL_POP) || string.IsNullOrEmpty(MAIL_SENDER) || string.IsNullOrEmpty(PRT_COUNT) || string.IsNullOrEmpty(COMPANY_NAME)) { QueryUser(); } try { popMail.Connect(MAIL_POP, HtmlTextPath.EMAIL_PORT, false); } catch (Exception ex) { Console.Out.WriteLine("ex:" + ex); SetRichTextValue(DateTime.Now.ToString("o") + @"######Internet connection failed######"); return; //throw; } //登录邮箱地址 popMail.Login(MAIL_USER_NAME, MAIL_USER_PWD); } catch (Exception ex) { Console.Out.WriteLine("ex:" + ex); //richTextBox1.Text += System.Environment.NewLine + "ex:" + ex; //Console.Out.WriteLine("Can not connect email server" + DateTime.Now.ToString("o")); //richTextBox1.Text += System.Environment.NewLine + "Can not connect email server:" + DateTime.Now.ToString("o"); //SetRichTextValue("MAIL_USER_NAME:" + MAIL_USER_NAME + "MAIL_USER_PWD:" + MAIL_USER_PWD + "MAIL_POP:" + MAIL_POP + "MAIL_SENDER:" + MAIL_SENDER + "PRT_COUNT:" + PRT_COUNT + "COMPANY_NAME:" + COMPANY_NAME); SetRichTextValue(DateTime.Now.ToString("o") + @"######Can not connect email server######"); return; } Console.Out.WriteLine(DateTime.Now.ToString("o")); SetRichTextValue(DateTime.Now.ToString("o")); POP3_ClientMessageCollection messagesCollection = popMail.Messages; POP3_ClientMessage message = null; //存放需删除的邮件 List <POP3_ClientMessage> lstMessage = new List <POP3_ClientMessage>(); string strMessage = ""; if (0 < messagesCollection.Count) { //for (int i = messagesCollection.Count - 1; i >= 0; i--) for (var index = 0; index < popMail.Messages.Count; index++) { POP3_ClientMessage mail = popMail.Messages[index]; try { message = mail; } catch (Exception) { popMail.Timeout = HtmlTextPath.EMAIL_TIME_OUT; popMail.Connect(MAIL_POP, HtmlTextPath.EMAIL_PORT, true); popMail.Login(MAIL_USER_NAME, MAIL_USER_PWD); } Mail_Message mailMessage = null; try { if (message != null) { byte[] messBytes = message.MessageToByte(); mailMessage = Mail_Message.ParseFromByte(messBytes); } else { continue; } } catch (Exception) { SetRichTextValue(DateTime.Now.ToString("o") + @"ERR GET MSG TO BYTE"); continue; //Console.WriteLine(@"ERR GET MSG TO BYTE:" + DateTime.Now.ToString("o")); //throw; } sendmail = mailMessage.From[0].Address; HtmlBody = mailMessage.BodyHtmlText; if (!sendmail.Equals(MAIL_SENDER)) { message.MarkForDeletion(); SetRichTextValue(DateTime.Now.ToString("o") + @"######===" + sendmail + "===Message discarded#####"); continue; } //PrtOrder(HtmlBody.Replace("脳", "×").Replace("拢", "£")); //PrtOrderWithTemplate(HtmlBody); if (VERSION.Equals("2")) { HtmlBody = HtmlBody.Replace("<body style=\"", "<body style=\"font-family:Arial; "); } else if (VERSION.Equals("3")) { HtmlBody = HtmlBody.Replace("<body", "<body style=\"font-family:Arial; \""); } //读取Html失败时,跳出循环 if (!GetPrtInfo(HtmlBody)) { message.MarkForDeletion(); SetRichTextValue(DateTime.Now.ToString("o") + @"######===" + orderId + "===OLD Message discarded#####"); continue; } ////DataGridView中的订单号不能重复 //for (int j = 0; j < dgvOrder.RowCount; j++) //{ // if (dgvOrder.Rows[j].Cells[0].Value != null) // { // if (!string.IsNullOrEmpty(dgvOrder.Rows[j].Cells[0].Value.ToString())) // { // if (dgvOrder.Rows[j].Cells[0].Value.ToString().Equals(orderId)) // { // message.MarkForDeletion(); // SetRichTextValue(DateTime.Now.ToString("o") + @"######===" + orderId + "===DGV Message discarded#####"); // continue; // } // } // } //} //存在订单时不打印 //if (SqlHelper.QueryId(@"SELECT mailID FROM Mail_ID WHERE orderID='" + orderId + "'")) //{ // SetRichTextValue(DateTime.Now.ToString("o") + @"######Duplicate order ID######"); // continue; //} if (VERSION.Equals("2")) { HtmlBody = HtmlBody.Replace("h1", "h4").Replace("<p>", "").Replace("</p>", "<br />") .Replace("<p style=\"width:94%;\">", "").Replace("<strong>", "").Replace("</strong>", ""); //HtmlBody = HtmlBody.Replace("h1", "h5"); HtmlBody = HtmlBody.Replace("<h4>", "").Replace("</h4>", "").Replace("<b>", "") .Replace("</b>", "") .Replace("border-top:hidden;", "").Replace("style=\"border-top:hidden;\"", ""); } else if (VERSION.Equals("3")) { //中文字体更大一号字体 HtmlBody = HtmlBody.Replace("<span style=\"font-size:18px;\">", "<span style=\"font-size:24px;\">"); HtmlBody = HtmlBody.Replace("h1", "h4").Replace("<p>", "").Replace("</p>", "<br />") .Replace("<p style=\"width:94%;\">", "").Replace("<strong>", "").Replace("</strong>", ""); //HtmlBody = HtmlBody.Replace("h1", "h5"); HtmlBody = HtmlBody.Replace("<h4>", "").Replace("</h4>", "").Replace("<b>", "") .Replace("</b>", "") .Replace("border-top:hidden;", "").Replace("style=\"border-top:hidden;\"", ""); } //打印完成后插入数据 if (!SqlHelper.InsertId( @"INSERT INTO Mail_ID(mailID, orderID, orderType, orderTime, orderHtmlBody) VALUES('" + mail.UID + "', '" + orderId + "', '" + orderType + "', '" + orderDate + "', '')")) { MessageBox.Show(@"WRITE Data Error!", @"ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { //int index = this.dgvOrder.Rows.Add(); this.dgvOrder.Rows.Insert(0, dgvOrder.Rows); dgvOrder.Rows[0].Cells[0].Value = orderId; dgvOrder.Rows[0].Cells[1].Value = orderDate; dgvOrder.Rows[0].Cells[2].Value = orderType; dgvOrder.Rows[0].Cells[3].Value = HtmlBody; dgvOrder.Refresh(); } //播放语音提示 if (File.Exists(Environment.CurrentDirectory + wavNewMail)) { SoundPlayer player = new SoundPlayer(Environment.CurrentDirectory + wavNewMail); player.Play(); } SetRichTextValue(@"#Time Printing order number=" + orderId); PrtContent(HtmlBody); //完成后添加删除邮件 lstMessage.Add(message); } for (int i = lstMessage.Count - 1; i >= 0; i--) { try { lstMessage[i].MarkForDeletion(); Console.WriteLine(@"DELETE MAIL DONE:" + DateTime.Now.ToString("o")); } catch (Exception) { Console.WriteLine(@"DELETE MAIL FAILURE:" + DateTime.Now.ToString("o")); //throw; } } if (popMail != null) { //popMail = null; try { popMail.Disconnect(); } catch (Exception) { //Console.Out.WriteLine("Error if (popMail != null)"); SetRichTextValue(@"Error POPMail != null"); } } } else { try { SetRichTextValue(DateTime.Now.ToString("o") + @"#No mail received#"); popMail.Disconnect(); } catch (Exception) { //Console.Out.WriteLine("Error else"); SetRichTextValue(@"Error ELSE"); } } }
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("登陆失败"); } }
private bool ProcessNewComment(List <string> recipients, POP3_ClientMessage message, Mail_Message mailHeader, MailboxReaderResult result) { string messageFrom = string.Empty; if (mailHeader.From.Count > 0) { messageFrom = string.Join("; ", mailHeader.From.ToList().Select(p => p.Address).ToArray()).Trim(); } bool processed = false; foreach (var address in recipients) { Regex isReply = new Regex(@"(.*)(\+iid-)(\d+)@(.*)"); Match commentMatch = isReply.Match(address); if (commentMatch.Success && commentMatch.Groups.Count >= 4) { // we are in a reply and group 4 must contain the id of the original issue int issueId; if (int.TryParse(commentMatch.Groups[3].Value, out issueId)) { var _currentIssue = IssueManager.GetById(issueId); if (_currentIssue != null) { var project = ProjectManager.GetById(_currentIssue.ProjectId); var mailbody = Mail_Message.ParseFromByte(message.MessageToByte()); bool isHtml; List <MIME_Entity> attachments = null; string content = GetMessageContent(mailbody, project, out isHtml, ref attachments); IssueComment comment = new IssueComment { IssueId = issueId, Comment = content, DateCreated = mailHeader.Date }; // try to find if the creator is valid user in the project, otherwise take // the user defined in the mailbox config var users = UserManager.GetUsersByProjectId(project.Id); var emails = messageFrom.Split(';').Select(e => e.Trim().ToLower()); var user = users.Find(x => emails.Contains(x.Email.ToLower())); if (user != null) { comment.CreatorUserName = user.UserName; } else { // user not found continue; } var saved = IssueCommentManager.SaveOrUpdate(comment); if (saved) { //add history record var history = new IssueHistory { IssueId = issueId, CreatedUserName = comment.CreatorUserName, DateChanged = comment.DateCreated, FieldChanged = ResourceStrings.GetGlobalResource(GlobalResources.SharedResources, "Comment", "Comment"), OldValue = string.Empty, NewValue = ResourceStrings.GetGlobalResource(GlobalResources.SharedResources, "Added", "Added"), TriggerLastUpdateChange = true }; IssueHistoryManager.SaveOrUpdate(history); var projectFolderPath = Path.Combine(Config.UploadsFolderPath, project.UploadPath); // save attachments as new files int attachmentsSavedCount = 1; foreach (MIME_Entity mimeEntity in attachments) { string fileName; var contentType = mimeEntity.ContentType.Type.ToLower(); var attachment = new IssueAttachment { Id = 0, Description = "File attached by mailbox reader", DateCreated = DateTime.Now, ContentType = mimeEntity.ContentType.TypeWithSubtype, CreatorDisplayName = user.DisplayName, CreatorUserName = user.UserName, IssueId = issueId, ProjectFolderPath = projectFolderPath }; attachment.Attachment = ((MIME_b_SinglepartBase)mimeEntity.Body).Data; if (contentType.Equals("attachment")) // this is an attached email { fileName = mimeEntity.ContentDisposition.Param_FileName; } else if (contentType.Equals("message")) // message has no filename so we create one { fileName = string.Format("Attached_Message_{0}.eml", attachmentsSavedCount); } else { fileName = string.IsNullOrWhiteSpace(mimeEntity.ContentType.Param_Name) ? string.Format("untitled.{0}", mimeEntity.ContentType.SubType) : mimeEntity.ContentType.Param_Name; } attachment.FileName = fileName; var saveFile = IsAllowedFileExtension(fileName); var fileSaved = false; // can we save the file? if (saveFile) { fileSaved = IssueAttachmentManager.SaveOrUpdate(attachment); if (fileSaved) { attachmentsSavedCount++; } else { LogWarning("MailboxReader: Attachment could not be saved, please see previous logs"); } } } processed = true; // add the entry if the save did not throw any exceptions result.MailboxEntries.Add(new MailboxEntry()); } } } } } return(processed); }
private bool ProcessNewIssue(List <string> recipients, POP3_ClientMessage message, Mail_Message mailHeader, IList <Project> projects, MailboxReaderResult result) { var messageFrom = string.Empty; if (mailHeader.From.Count > 0) { messageFrom = string.Join("; ", mailHeader.From.ToList().Select(p => p.Address).ToArray()).Trim(); } bool processed = false; // 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()); bool isHtml; List <MIME_Entity> attachments = null; string content = GetMessageContent(mailbody, project, out isHtml, ref attachments); entry.Content = content; entry.IsHtml = isHtml; foreach (var attachment in attachments) { entry.MailAttachments.Add(attachment); } //save this message Issue issue = SaveMailboxEntry(entry); //send notifications for the new issue SendNotifications(issue); // add the entry if the save did not throw any exceptions result.MailboxEntries.Add(entry); processed = true; } return(processed); }
private static Mail IndexMessage(POP3_ClientMessage sampleMessage) { var messageBytes = sampleMessage.MessageToByte(); var mimeMessage = Mail_Message.ParseFromByte(messageBytes); var body = mimeMessage.BodyText ?? "Content is null"; Console.WriteLine("Body: {0}", body); var mail = new Mail(); var from = mimeMessage.From; if (null != from) { mail.From = from.ToArray().Select(m => m.Address).ToArray(); } var to = mimeMessage.To; if (null != to) { mail.To = to.Mailboxes.Select(m => m.Address).ToArray(); } var cc = mimeMessage.Cc; if (null != cc) { mail.Cc = cc.Mailboxes.Select(m => m.Address).ToArray(); } var bcc = mimeMessage.Bcc; if (null != bcc) { mail.Bcc = bcc.Mailboxes.Select(m => m.Address).ToArray(); } mail.Subject = mimeMessage.Subject; mail.SentTime = mimeMessage.Date; var attachments = mimeMessage.Attachments; if (null == attachments || 0 == attachments.Length) { return(mail); } //获取原件 var originMail = attachments[0]; var originMailBody = originMail.Body as MIME_b_MessageRfc822; var originMailMessage = originMailBody?.Message; if (originMailMessage != null) { mail.Body = originMailMessage.BodyText; mail.MessageId = originMailMessage.MessageID; } var attachmentCount = attachments.Length - 1; if (attachmentCount <= 0) { return(mail); } //获取附件 var attachmentNameList = new List <string>(); for (int i = 0; i < attachmentCount; i++) { var attachment = attachments[i + 1]; var attachmentName = attachment.ContentDescription; if (string.IsNullOrEmpty(attachmentName)) { var attachmentMailBody = attachment.Body as MIME_b_MessageRfc822; var attachmentMailMessage = attachmentMailBody?.Message; if (null != attachmentMailMessage) { attachmentName = attachmentMailMessage.Subject; } if (string.IsNullOrEmpty(attachmentName)) { attachmentName = attachment.Body?.MediaType; } } attachmentNameList.Add(attachmentName); } if (attachmentNameList.Count > 0) { mail.Attachments = attachmentNameList.ToArray(); } //mail.Body = mimeMessage.BodyText; return(mail); }