/// <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; } } }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="mediaType">MIME media type. For example: text/plain.</param> /// <param name="stream">Stream from where to read body.</param> /// <returns>Returns parsed body.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b>, <b>mediaType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected new static MIME_b Parse(MIME_Entity owner, string mediaType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } if (stream == null) { throw new ArgumentNullException("stream"); } MIME_b_MessageRfc822 retVal = new MIME_b_MessageRfc822(); if (owner.ContentTransferEncoding != null && owner.ContentTransferEncoding.Equals("base64", StringComparison.OrdinalIgnoreCase)) { Stream decodedDataStream = new MemoryStream(); using (StreamReader reader = new StreamReader(stream)) { byte[] decoded = Convert.FromBase64String(reader.ReadToEnd()); decodedDataStream.Write(decoded, 0, decoded.Length); decodedDataStream.Seek(0, SeekOrigin.Begin); } //Create base64 decoder stream = new SmartStream(decodedDataStream, true); } retVal.m_pMessage = Mail_Message.ParseFromStream(stream); return(retVal); }
private static string GetMailMessage(Mail_Message message) { string html = FindHtmlInMessage(message); string plainText = FindPlainTextInMessage(message); return(!string.IsNullOrWhiteSpace(html) ? html : plainText); }
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); }
/// <summary> /// Raises <b>NewMessageData</b> event. /// </summary> /// <param name="msgInfo">IMAP message info which message data it is.</param> /// <param name="msgData">Message data. NOTE: This value must be as specified by <see cref="IMAP_e_Fetch.FetchDataType"/>.</param> private void OnNewMessageData(IMAP_MessageInfo msgInfo, Mail_Message msgData) { if (this.NewMessageData != null) { this.NewMessageData(this, new e_NewMessageData(msgInfo, msgData)); } }
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(); } }
/// <summary> /// Checks that the specified SmtpMessage has a body that contains the specified string /// </summary> /// <param name="smtpMessage">The SMTP message.</param> /// <param name="expectedBodyPortion">The expected body.</param> /// <returns></returns> public static Mail_Message ShouldHaveBodyThatContains(this Mail_Message smtpMessage, string expectedBodyPortion) { // Confirm that we have the expected body substring var removed = smtpMessage.BodyText.Replace("=" + System.Environment.NewLine, ""); Assert.IsTrue(removed.Contains(expectedBodyPortion), "Email message body doesn't contain expected substring"); return(smtpMessage); }
public RelayVariablesManager(RelayServer server, Relay_Session relaySession, string errorText, Mail_Message message) { this.m_pRelayServer = server; this.m_pRelaySession = relaySession; this.m_ErrorText = errorText; this.m_pMessageStream = relaySession.MessageStream; this.m_pMime = message; }
public static string ConstructBodyStructure(Mail_Message message, bool bodystructure) { if (bodystructure) { return("BODYSTRUCTURE " + IMAP_BODY.ConstructParts(message, bodystructure)); } return("BODY " + IMAP_BODY.ConstructParts(message, bodystructure)); }
/// <summary> /// Checks that the specified SmtpMessage has the expected recipient /// </summary> /// <param name="smtpMessage">The SMTP message.</param> /// <param name="expectedRecipientEmailAddress">The expected recipient email address.</param> /// <returns></returns> public static Mail_Message ShouldBeTo(this Mail_Message smtpMessage, string expectedRecipientEmailAddress) { var address = smtpMessage.To.OfType <Mail_t_Mailbox>().Select(o => o.Address).Single(); Assert.AreEqual(address, expectedRecipientEmailAddress, "Missing To email address {0}", expectedRecipientEmailAddress); return(smtpMessage); }
internal void Update(Mail_Message origin) { this.origin = origin; this.MsgID = origin.MessageID; this.Subject = origin.Subject; this.Date = origin.Date; if (origin.From != null && origin.From.Count > 0) { this.From = new MailboxList(); for (int i = 0; i < origin.From.Count; i++) { this.From.Add(new Mailbox { DisplayName = origin.From[i].DisplayName, Address = origin.From[i].Address, Domain = origin.From[i].Domain }); } } if (origin.To != null && origin.To.Count > 0) { this.To = new AddressList(); foreach (Mail_t_Address address in origin.To) { this.To.Add(address.ToString()); } } else { this.To = null; } if (origin.Cc != null && origin.Cc.Count > 0) { this.Cc = new AddressList(); foreach (Mail_t_Address address in origin.Cc) { this.Cc.Add(address.ToString()); } } else { this.Cc = null; } if (origin.Attachments != null && origin.Attachments.Length > 0) { this.Attachments = new List <IAttachment>(); for (int i = 0; i < origin.Attachments.Length; i++) { this.Attachments.Add(new Pop3Attachment(origin.Attachments[i])); } } else { this.Attachments = null; } }
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(); } }
private void OnSessionMessageStoringCompleted(object sender, SMTP_e_MessageStored e) { _log.Debug("begin processing message storing completed event"); try { e.Stream.Flush(); e.Stream.Seek(0, SeekOrigin.Begin); Mail_Message message = Mail_Message.ParseFromStream(e.Stream); message.Subject = Regex.Replace(message.Subject, @"\t", ""); foreach (var requestInfo in e.Session.To .Where(x => e.Session.Tags.ContainsKey(x.Mailbox)) .Select(x => (ApiRequest)e.Session.Tags[x.Mailbox])) { try { _log.Debug("begin process request (" + requestInfo + ")"); CoreContext.TenantManager.SetCurrentTenant(requestInfo.Tenant); if (requestInfo.Parameters != null) { foreach (var parameter in requestInfo.Parameters.Where(x => x.ValueResolver != null)) { parameter.Value = parameter.ValueResolver.ResolveParameterValue(message); } } if (requestInfo.FilesToPost != null) { requestInfo.FilesToPost = message.AllEntities.Where(IsAttachment).Select(GetAsAttachment).ToList(); } if (requestInfo.FilesToPost == null || requestInfo.FilesToPost.Count > 0) { _apiService.EnqueueRequest(requestInfo); } _log.Debug("end process request (" + requestInfo + ")"); } catch (Exception ex) { _log.Error("error while processing request info", ex); } } } catch (Exception error) { _log.Error("error while processing message storing completed event", error); } finally { e.Stream.Close(); } _log.Debug("complete processing message storing completed event"); }
private static string FindHtmlInMessage(Mail_Message message) { if (!string.IsNullOrWhiteSpace(message.BodyHtmlText)) { return(message.BodyHtmlText); } return(string.Empty); }
/// <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(""); }
/// <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); }
/// <summary> /// Checks that the specified SmtpMessage has a subject that contains the specified string /// </summary> /// <param name="smtpMessage">The SMTP message.</param> /// <param name="expectedSubjectPortion">The expected subject portion.</param> /// <returns></returns> public static Mail_Message ShouldHaveSubjectThatContains(this Mail_Message smtpMessage, string expectedSubjectPortion) { // Confirm that we have the expected subject var actualSubject = smtpMessage.Header; Assert.IsTrue(actualSubject.Contains(expectedSubjectPortion), "Email message subject doesn't contain expected substring"); return(smtpMessage); }
public object ResolveParameterValue(Mail_Message mailMessage) { if (!Pattern.IsMatch(mailMessage.Subject)) { return(null); } return(Convert.ToInt32(Pattern.Match(mailMessage.Subject).Value)); }
/// <summary> /// Default constructor. /// </summary> /// <param name="msgInfo">Message info.</param> /// <param name="msgData">Message data stream.</param> /// <exception cref="ArgumentNullException">Is raised when <b>msgInfo</b> is null reference.</exception> public e_NewMessageData(IMAP_MessageInfo msgInfo, Mail_Message msgData) { if (msgInfo == null) { throw new ArgumentNullException("msgInfo"); } m_pMsgInfo = msgInfo; m_pMsgData = msgData; }
/// <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 object ResolveParameterValue(Mail_Message mailMessage) { var messageText = new HtmlContentResolver().ResolveParameterValue(mailMessage) as string; if (!string.IsNullOrEmpty(messageText)) { messageText = Html2TextConverter.Convert(messageText); } return(messageText); }
/// <summary> /// Checks that the specified SmtpMessage has the expected subject /// </summary> /// <param name="smtpMessage">The SMTP message.</param> /// <param name="expectedSubject">The expected subject.</param> /// <returns></returns> public static Mail_Message ShouldHaveSubject(this Mail_Message smtpMessage, string expectedSubject) { // Confirm that we have the expected subject var actualSubject = smtpMessage.Subject; Assert.AreEqual(expectedSubject, actualSubject, "Email message subject incorrect"); return(smtpMessage); }
public object ResolveParameterValue(Mail_Message mailMessage) { if (!Pattern.IsMatch(mailMessage.Subject)) { return(null); } var match = Pattern.Match(mailMessage.Subject); return(new DateTime(Convert.ToInt32(match.Groups["year"].Value), Convert.ToInt32(match.Groups["month"].Value), Convert.ToInt32(match.Groups["day"].Value))); }
/// <summary> /// Checks the received message has the correct number of attachments. /// </summary> /// <param name="smtpMessage">The SMTP message.</param> /// <param name="numberOfAttachments">The number of attachments.</param> /// <returns></returns> public static Mail_Message ShouldHaveAttachments(this Mail_Message smtpMessage, int numberOfAttachments) { // Confirm that we have the requested number of emails var actualAttachmentCount = smtpMessage.Attachments.Length; Assert.AreEqual(numberOfAttachments, actualAttachmentCount, "Email attachment count incorrect"); return(smtpMessage); }
public void rtf_email_with_image_attachment_has_one_attachment() { var result = Mail_Message.ParseFromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream("BugNET.MailboxReader.Tests.rtf_email_with_image_attachment.txt")); var attachments = result.GetAttachments(true); Assert.AreEqual(1, attachments.Length, "rtf email had {0} attachments we expected {1}", attachments.Length, 1); var mimeEntity = attachments[0].Body.Entity; Assert.AreEqual("image", mimeEntity.ContentType.Type, "email has attachment type {0} we expected {1}", mimeEntity.ContentType.Type, "image"); }
/// <summary> /// Creates Mime message based on UI data. /// </summary> private Mail_Message CreateMessage() { Mail_Message msg = new Mail_Message(); msg.MimeVersion = "1.0"; msg.MessageID = MIME_Utils.CreateMessageID(); msg.Date = DateTime.Now; msg.From = Mail_h_MailboxList.Parse("From: " + m_pFrom.Text).Addresses; msg.To = new Mail_t_AddressList(); msg.To.Add(new Mail_t_Mailbox(m_pFolder.User.FullName, m_pFolder.User.FullName + "@localhost")); msg.Subject = m_pSubject.Text; //--- multipart/mixed ------------------------------------------------------------------------------------------------- MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed); contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed); msg.Body = multipartMixed; //--- multipart/alternative ----------------------------------------------------------------------------------------- MIME_Entity entity_multipartAlternative = new MIME_Entity(); MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative); contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative); entity_multipartAlternative.Body = multipartAlternative; multipartMixed.BodyParts.Add(entity_multipartAlternative); //--- text/plain ---------------------------------------------------------------------------------------------------- MIME_Entity entity_text_plain = new MIME_Entity(); MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain); entity_text_plain.Body = text_plain; text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, m_pText.Text); multipartAlternative.BodyParts.Add(entity_text_plain); //--- text/html ------------------------------------------------------------------------------------------------------ MIME_Entity entity_text_html = new MIME_Entity(); MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html); entity_text_html.Body = text_html; text_html.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, RtfToHtml()); multipartAlternative.BodyParts.Add(entity_text_html); //--- application/octet-stream ----------------------------------------------------------------------------------------------- foreach (ListViewItem item in m_pAttachments.Items) { multipartMixed.BodyParts.Add(Mail_Message.CreateAttachment(item.Tag.ToString())); } return(msg); }
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); }
public object ResolveParameterValue(Mail_Message mailMessage) { var subject = mailMessage.Subject; foreach (var pattern in _ignorePatterns) { subject = pattern.Replace(subject, ""); } return(Regex.Replace(subject, @"\s+", " ").Trim(' ')); }
public object ResolveParameterValue(Mail_Message mailMessage) { var messageText = !string.IsNullOrEmpty(mailMessage.BodyHtmlText) ? mailMessage.BodyHtmlText : Text2HtmlConverter.Convert(mailMessage.BodyText.Trim(' ')); messageText = messageText.Replace(Environment.NewLine, "").Replace(@"\t", ""); messageText = HtmlEntity.DeEntitize(messageText); messageText = HtmlSanitizer.Sanitize(messageText); return(messageText.Trim("<br>").Trim("</br>").Trim(' ')); }
/// <summary> /// Adds specified message for FETCH response processing. /// </summary> /// <param name="msgInfo">IMAP message info which message data it is.</param> /// <param name="msgData">Message data. NOTE: This value must be as specified by <see cref="IMAP_e_Fetch.FetchDataType"/>.</param> /// <exception cref="ArgumentNullException">Is raised when <b>msgInfo</b> or <b>msgData</b> is null reference.</exception> public void AddData(IMAP_MessageInfo msgInfo, Mail_Message msgData) { if (msgInfo == null) { throw new ArgumentNullException("msgInfo"); } if (msgData == null) { throw new ArgumentNullException("msgData"); } OnNewMessageData(msgInfo, msgData); }
/// <summary> /// Default constructor. /// </summary> /// <param name="msgInfo">Message info.</param> /// <param name="msgData">Message data stream.</param> /// <exception cref="ArgumentNullException">Is raised when <b>msgInfo</b> is null reference.</exception> public e_NewMessageData(IMAP_MessageInfo msgInfo,Mail_Message msgData) { if(msgInfo == null){ throw new ArgumentNullException("msgInfo"); } m_pMsgInfo = msgInfo; m_pMsgData = msgData; }
/// <summary> /// Default constructor. /// </summary> public MIME_b_MessageRfc822() : base(new MIME_h_ContentType("message/rfc822")) { m_pMessage = new Mail_Message(); }