/// <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 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"); }
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"); }
public void html_email_with_bad_header_has_one_image_attachment() { // with the bad header for some reason this email inline attachments are missing GetAttachments process via the body boundaries // rather than the layout of the boundaries in the email. var result = Mail_Message.ParseFromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream("BugNET.MailboxReader.Tests.html_email_with_bad_header.txt")); var attachments = result.GetAttachments(true); Assert.AreEqual(1, attachments.Length, "html 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> /// This method is called when FETCH RFC822 untagged response is received. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void FetchMessageHandler(object sender, EventArgs <IMAP_r_u> e) { /* NOTE: All IMAP untagged responses may be raised from thread pool thread, * so all UI operations must use Invoke. * * There may be other untagged responses than FETCH, because IMAP server * may send any untagged response to any command. */ var resp = e.Value as IMAP_r_u_Fetch; if (resp == null) { return; } var fetchResp = resp; try { if (fetchResp.Rfc822 == null) { return; } fetchResp.Rfc822.Stream.Position = 0; var mime = Mail_Message.ParseFromStream(fetchResp.Rfc822.Stream); fetchResp.Rfc822.Stream.Dispose(); _curMessage.TextBody = string.IsNullOrWhiteSpace(mime.BodyText) ? mime.BodyHtmlText : mime.BodyText; _curMessage.Attachments.Clear(); var i = 0; foreach (var entity in mime.Attachments) { var attachment = new Attachment(); i++; if (entity.ContentDisposition?.Param_FileName != null) { attachment.Text = entity.ContentDisposition.Param_FileName; } else { attachment.Text = "untitled" + i; } attachment.Body = ((MIME_b_SinglepartBase)entity.Body).Data; _curMessage.Attachments.Add(attachment); } } catch (Exception ex) { //Debug.WriteLine("EmailImapTransport: FetchMessageHandler: " + ex.Message); AppJournal.Write("EmailImapTransport: FetchMessageHandler: " + ex.Message); } }
/// <summary> /// Stores specified message to this folder. Message storing begins from stream current position. /// </summary> /// <param name="message">Message to store.</param> public void StoreMessage(Stream message) { long pos = message.Position; try{ Mail_Message.ParseFromStream(message); } catch { throw new Exception("Specified message is not valid message or is corrupt !"); } message.Position = pos; /* C: StoreUserFolderMessage <virtualServerID> "<folderOwnerUser>" "<folder>" <sizeInBytes> * S: +OK Send message data * C: <messageData> * S: +OK * * Responses: +OK * -ERR <errorText> */ m_pUser.VirtualServer.Server.TcpClient.TcpStream.WriteLine("StoreUserFolderMessage " + m_pUser.VirtualServer.VirtualServerID + " " + TextUtils.QuoteString(m_pUser.UserName) + " " + TextUtils.QuoteString(this.FolderFullPath) + " " + (message.Length - message.Position).ToString() ); string response = m_pUser.VirtualServer.Server.ReadLine(); if (!response.ToUpper().StartsWith("+OK")) { throw new Exception(response); } m_pUser.VirtualServer.Server.TcpClient.TcpStream.WriteStream(message); response = m_pUser.VirtualServer.Server.ReadLine(); if (!response.ToUpper().StartsWith("+OK")) { throw new Exception(response); } }
private void Send_DSN_Relayed(Relay_Session session) { if (session == null) { return; } try { if (!string.IsNullOrEmpty(session.From)) { RelayMessageInfo relayMessageInfo = (RelayMessageInfo)session.QueueTag; if ((relayMessageInfo.DSN_Notify & SMTP_DSN_Notify.Success) != SMTP_DSN_Notify.NotSpecified) { session.MessageStream.Position = 0L; Mail_Message mail_Message = Mail_Message.ParseFromStream(session.MessageStream); RelayVariablesManager relayVariablesManager = new RelayVariablesManager(this, session, "", mail_Message); ServerReturnMessage serverReturnMessage = null; if (serverReturnMessage == null) { string bodyTextRft = "{\\rtf1\\ansi\\ansicpg1257\\deff0\\deflang1061{\\fonttbl{\\f0\\froman\\fcharset0 Times New Roman;}{\\f1\froman\\fcharset186{\\*\\fname Times New Roman;}Times New Roman Baltic;}{\\f2\fswiss\\fcharset186{\\*\\fname Arial;}Arial Baltic;}}\r\n{\\colortbl ;\\red0\\green128\\blue0;\\red128\\green128\\blue128;}\r\n{\\*\\generator Msftedit 5.41.21.2508;}\\viewkind4\\uc1\\pard\\sb100\\sa100\\lang1033\\f0\\fs24\\par\r\nYour message WAS SUCCESSFULLY RELAYED to:\\line\\lang1061\\f1\\tab\\cf1\\lang1033\\b\\f0 <" + session.To + ">\\line\\cf0\\b0 and you explicitly requested a delivery status notification on success.\\par\\par\r\n\\cf2 Your original message\\lang1061\\f1 /header\\lang1033\\f0 is attached to this e-mail\\lang1061\\f1 .\\lang1033\\f0\\par\\r\\n\\cf0\\line\\par\r\n\\pard\\lang1061\\f2\\fs20\\par\r\n}\r\n"; serverReturnMessage = new ServerReturnMessage("DSN SUCCESSFULLY RELAYED: <#message.header[\"Subject:\"]>", bodyTextRft); } string rtfText = relayVariablesManager.Process(serverReturnMessage.BodyTextRtf); Mail_Message mail_Message2 = DeliveryStatusNotification.CreateDsnMessage(session.From, relayVariablesManager.Process(serverReturnMessage.Subject), rtfText, relayMessageInfo.EnvelopeID, relayMessageInfo.Date, null, (session.IsConnected && string.IsNullOrEmpty(session.LocalHostName)) ? session.LocalEndPoint.Address.ToString() : session.LocalHostName, relayMessageInfo.OriginalRecipient, session.To, "relayed", "200 OK", session.RemoteHostName, DateTime.MinValue, DateTime.MinValue, (relayMessageInfo.DSN_Ret == SMTP_DSN_Ret.NotSpecified) ? SMTP_DSN_Ret.Headers : relayMessageInfo.DSN_Ret, mail_Message); using (MemoryStream memoryStream = new MemoryStream()) { mail_Message2.ToStream(memoryStream, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8); this.m_pVirtualServer.ProcessAndStoreMessage("", new string[] { session.From }, memoryStream, null); } mail_Message.Dispose(); mail_Message2.Dispose(); } } } catch (Exception x) { DataSmart.MailServer.Error.DumpError(this.m_pVirtualServer.Name, x); } }
/// <summary> /// Parses body from the specified stream /// </summary> /// <param name="owner">Owner MIME entity.</param> /// <param name="defaultContentType">Default content-type for this body.</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>defaultContentType</b> or <b>stream</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when any parsing errors.</exception> protected static new MIME_b Parse(MIME_Entity owner, MIME_h_ContentType defaultContentType, SmartStream stream) { if (owner == null) { throw new ArgumentNullException("owner"); } if (defaultContentType == null) { throw new ArgumentNullException("defaultContentType"); } if (stream == null) { throw new ArgumentNullException("stream"); } MIME_b_MessageRfc822 retVal = new MIME_b_MessageRfc822(); retVal.m_pMessage = Mail_Message.ParseFromStream(stream); return(retVal); }
private void Send_DSN_Delayed(Relay_Session session, string error) { try { if (!string.IsNullOrEmpty(session.From)) { RelayMessageInfo relayMessageInfo = (RelayMessageInfo)session.QueueTag; if (relayMessageInfo.DSN_Notify == SMTP_DSN_Notify.NotSpecified || (relayMessageInfo.DSN_Notify & SMTP_DSN_Notify.Delay) != SMTP_DSN_Notify.NotSpecified) { session.MessageStream.Position = 0L; Mail_Message mail_Message = Mail_Message.ParseFromStream(session.MessageStream); RelayVariablesManager relayVariablesManager = new RelayVariablesManager(this, session, error, mail_Message); ServerReturnMessage serverReturnMessage = this.DelayedDeliveryMessage; if (serverReturnMessage == null) { string bodyTextRft = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fnil\\fcharset0 Verdana;}{\\f1\\fnil\\fcharset186 Verdana;}{\\f2\\fswiss\\fcharset186{\\*\\fname Arial;}Arial Baltic;}{\\f3\\fnil\\fcharset0 Microsoft Sans Serif;}}\r\n{\\colortbl ;\\red0\\green64\\blue128;\\red255\\green0\\blue0;\\red0\\green128\\blue0;}\r\n\\viewkind4\\uc1\\pard\\f0\\fs20 This e-mail is generated by the Server(\\cf1 <#relay.hostname>\\cf0 ) to notify you, \\par\r\n\\lang1061\\f1 that \\lang1033\\f0 your message to \\cf1 <#relay.to>\\cf0 dated \\b\\fs16 <#message.header[\"Date:\"]>\\b0 \\fs20 could not be sent at the first attempt.\\par\r\n\\par\r\nRecipient \\i <#relay.to>'\\i0 s Server (\\cf1 <#relay.session_hostname>\\cf0 ) returned the following response: \\cf2 <#relay.error>\\cf0\\par\r\n\\par\r\n\\par\r\nPlease note Server will attempt to deliver this message for \\b <#relay.undelivered_after>\\b0 hours.\\par\r\n\\par\r\n--------\\par\r\n\\par\r\nYour original message is attached to this e-mail (\\b data.eml\\b0 )\\par\r\n\\par\r\n\\fs16 The tracking number for this message is \\cf3 <#relay.session_messageid>\\cf0\\fs20\\par\r\n\\lang1061\\f2\\par\r\n\\pard\\lang1033\\f3\\fs17\\par\r\n}\r\n"; serverReturnMessage = new ServerReturnMessage("Delayed delivery notice: <#message.header[\"Subject:\"]>", bodyTextRft); } string rtfText = relayVariablesManager.Process(serverReturnMessage.BodyTextRtf); Mail_Message mail_Message2 = DeliveryStatusNotification.CreateDsnMessage(session.From, relayVariablesManager.Process(serverReturnMessage.Subject), rtfText, relayMessageInfo.EnvelopeID, relayMessageInfo.Date, null, (session.IsConnected && string.IsNullOrEmpty(session.LocalHostName)) ? session.LocalEndPoint.Address.ToString() : session.LocalHostName, relayMessageInfo.OriginalRecipient, session.To, "delayed", error, session.RemoteHostName, DateTime.Now, relayMessageInfo.Date.AddMinutes((double)this.UndeliveredAfter), (relayMessageInfo.DSN_Ret == SMTP_DSN_Ret.NotSpecified) ? SMTP_DSN_Ret.FullMessage : relayMessageInfo.DSN_Ret, mail_Message); using (MemoryStream memoryStream = new MemoryStream()) { mail_Message2.ToStream(memoryStream, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8); this.m_pVirtualServer.ProcessAndStoreMessage("", new string[] { session.From }, memoryStream, null); } mail_Message.Dispose(); mail_Message2.Dispose(); } } } catch (Exception x) { DataSmart.MailServer.Error.DumpError(this.m_pVirtualServer.Name, x); } }
public void StoreMessage(Stream message) { long position = message.Position; try { Mail_Message.ParseFromStream(message); } catch { throw new Exception("Specified message is not valid message or is corrupt !"); } message.Position = position; this.m_pUser.VirtualServer.Server.TCP_Client.TcpStream.WriteLine(string.Concat(new string[] { "StoreUserFolderMessage ", this.m_pUser.VirtualServer.VirtualServerID, " ", TextUtils.QuoteString(this.m_pUser.UserName), " ", TextUtils.QuoteString(this.FolderFullPath), " ", (message.Length - message.Position).ToString() })); string text = this.m_pUser.VirtualServer.Server.ReadLine(); if (!text.ToUpper().StartsWith("+OK")) { throw new Exception(text); } this.m_pUser.VirtualServer.Server.TCP_Client.TcpStream.WriteStream(message); text = this.m_pUser.VirtualServer.Server.ReadLine(); if (!text.ToUpper().StartsWith("+OK")) { throw new Exception(text); } }
public static Mail_Message CreateDsnMessage(string to, string subject, string rtfText, string envelopeID, DateTime arrivalDate, string receivedFromMTA, string reportingMTA, string originalRecipient, string finalRecipient, string action, string statusCode_text, string remoteMTA, DateTime lastAttempt, DateTime retryUntil, SMTP_DSN_Ret ret, Mail_Message message) { rtfText = rtfText.Replace("\r\n", "\n").Replace("\n", "\r\n"); Mail_Message mail_Message = new Mail_Message(); mail_Message.MimeVersion = "1.0"; mail_Message.Date = DateTime.Now; mail_Message.From = new Mail_t_MailboxList(); mail_Message.From.Add(new Mail_t_Mailbox("Mail Delivery Subsystem", "postmaster@local")); mail_Message.To = new Mail_t_AddressList(); mail_Message.To.Add(new Mail_t_Mailbox(null, to)); mail_Message.Subject = subject; MIME_h_ContentType mIME_h_ContentType = new MIME_h_ContentType(MIME_MediaTypes.Multipart.report); mIME_h_ContentType.Parameters["report-type"] = "delivery-status"; mIME_h_ContentType.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartReport mIME_b_MultipartReport = new MIME_b_MultipartReport(mIME_h_ContentType); mail_Message.Body = mIME_b_MultipartReport; MIME_Entity mIME_Entity = new MIME_Entity(); MIME_b_MultipartAlternative mIME_b_MultipartAlternative = new MIME_b_MultipartAlternative(new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative) { Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.') }); mIME_Entity.Body = mIME_b_MultipartAlternative; mIME_b_MultipartReport.BodyParts.Add(mIME_Entity); MIME_Entity mIME_Entity2 = new MIME_Entity(); MIME_b_Text mIME_b_Text = new MIME_b_Text(MIME_MediaTypes.Text.plain); mIME_Entity2.Body = mIME_b_Text; mIME_b_Text.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, SCore.RtfToText(rtfText)); mIME_b_MultipartAlternative.BodyParts.Add(mIME_Entity2); MIME_Entity mIME_Entity3 = new MIME_Entity(); MIME_b_Text mIME_b_Text2 = new MIME_b_Text(MIME_MediaTypes.Text.html); mIME_Entity3.Body = mIME_b_Text2; mIME_b_Text2.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, SCore.RtfToHtml(rtfText)); mIME_b_MultipartAlternative.BodyParts.Add(mIME_Entity3); MIME_Entity mIME_Entity4 = new MIME_Entity(); MIME_b_Message mIME_b_Message = new MIME_b_Message(MIME_MediaTypes.Message.delivery_status); mIME_Entity4.Body = mIME_b_Message; StringBuilder stringBuilder = new StringBuilder(); if (!string.IsNullOrEmpty(envelopeID)) { stringBuilder.Append("Original-Envelope-Id: " + envelopeID + "\r\n"); } stringBuilder.Append("Arrival-Date: " + MIME_Utils.DateTimeToRfc2822(arrivalDate) + "\r\n"); if (!string.IsNullOrEmpty(receivedFromMTA)) { stringBuilder.Append("Received-From-MTA: dns; " + receivedFromMTA + "\r\n"); } stringBuilder.Append("Reporting-MTA: dns; " + reportingMTA + "\r\n"); stringBuilder.Append("\r\n"); if (!string.IsNullOrEmpty(originalRecipient)) { stringBuilder.Append("Original-Recipient: " + originalRecipient + "\r\n"); } stringBuilder.Append("Final-Recipient: rfc822;" + finalRecipient + "\r\n"); stringBuilder.Append("Action: " + action + "\r\n"); stringBuilder.Append("Status: " + statusCode_text.Substring(0, 1) + ".0.0\r\n"); if (!string.IsNullOrEmpty(statusCode_text)) { stringBuilder.Append("Diagnostic-Code: smtp; " + statusCode_text + "\r\n"); } if (!string.IsNullOrEmpty(remoteMTA)) { stringBuilder.Append("Remote-MTA: dns; " + remoteMTA + "\r\n"); } if (lastAttempt != DateTime.MinValue) { stringBuilder.Append("Last-Attempt-Date: " + MIME_Utils.DateTimeToRfc2822(lastAttempt) + "\r\n"); } if (retryUntil != DateTime.MinValue) { stringBuilder.Append("Will-Retry-Until: " + MIME_Utils.DateTimeToRfc2822(retryUntil) + "\r\n"); } stringBuilder.Append("\r\n"); mIME_b_Message.SetData(new MemoryStream(Encoding.UTF8.GetBytes(stringBuilder.ToString())), MIME_TransferEncodings.EightBit); mIME_b_MultipartReport.BodyParts.Add(mIME_Entity4); if (message != null) { MIME_Entity mIME_Entity5 = new MIME_Entity(); MIME_b_MessageRfc822 mIME_b_MessageRfc = new MIME_b_MessageRfc822(); mIME_Entity5.Body = mIME_b_MessageRfc; if (ret == SMTP_DSN_Ret.FullMessage) { mIME_b_MessageRfc.Message = message; } else { MemoryStream memoryStream = new MemoryStream(); message.Header.ToStream(memoryStream, null, null); memoryStream.Position = 0L; mIME_b_MessageRfc.Message = Mail_Message.ParseFromStream(memoryStream); } mIME_b_MultipartReport.BodyParts.Add(mIME_Entity5); } return(mail_Message); }
/// <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)); }
/// <summary> /// Creates and sends "Message delivery failed" to message sender. /// </summary> /// <param name="session">Relay_Session.</param> /// <param name="error">Permanent error happened.</param> private void Send_DSN_Failed(Relay_Session session, string error) { try{ // No sender specified, can't send notify, just skip it. if (string.IsNullOrEmpty(session.From)) { return; } RelayMessageInfo relayInfo = (RelayMessageInfo)session.QueueTag; // Send DSN only if user has not specified at all or has specified "failure". if (relayInfo.DSN_Notify != SMTP_DSN_Notify.NotSpecified && (relayInfo.DSN_Notify & SMTP_DSN_Notify.Failure) == 0) { return; } session.MessageStream.Position = 0; Mail_Message relayMessage = Mail_Message.ParseFromStream(session.MessageStream); RelayVariablesManager variablesMgr = new RelayVariablesManager(this, session, error, relayMessage); ServerReturnMessage messageTemplate = this.UndeliveredMessage; if (messageTemplate == null) { string bodyRtf = "" + "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fswiss\\fprq2\\fcharset0 Verdana;}{\\f1\\fswiss\\fprq2\\fcharset186 Verdana;}{\\f2\\fnil\\fcharset0 Verdana;}{\\f3\\fnil\\fcharset186 Verdana;}{\\f4\\fswiss\\fcharset0 Arial;}{\\f5\\fswiss\\fcharset186{\\*\\fname Arial;}Arial Baltic;}}\r\n" + "{\\colortbl ;\\red0\\green64\\blue128;\\red255\\green0\\blue0;\\red0\\green128\\blue0;}\r\n" + "\\viewkind4\\uc1\\pard\\f0\\fs20 Your message t\\lang1061\\f1 o \\cf1\\lang1033\\f2 <#relay.to>\\cf0\\f0 , dated \\b\\fs16 <#message.header[\"Date:\"]>\\b0\\fs20 , could not be delivered.\\par\r\n" + "\\par\r\n" + "Recipient \\i <#relay.to>'\\i0 s Server (\\cf1 <#relay.session_hostname>\\cf0 ) returned the following response: \\cf2 <#relay.error>\\cf0\\par\r\n" + "\\par\r\n" + "\\par\r\n" + "\\b * Server will not attempt to deliver this message anymore\\b0 .\\par\r\n" + "\\par\r\n" + "--------\\par\r\n" + "\\par\r\n" + "Your original message is attached to this e-mail (\\b data.eml\\b0 )\\par\r\n" + "\\par\r\n" + "\\fs16 The tracking number for this message is \\cf3 <#relay.session_messageid>\\cf0\\fs20\\par\r\n" + "\\lang1061\\f5\\par\r\n" + "\\lang1033\\f2\\par\r\n" + "}\r\n"; messageTemplate = new ServerReturnMessage("Undelivered notice: <#message.header[\"Subject:\"]>", bodyRtf); } string rtf = variablesMgr.Process(messageTemplate.BodyTextRtf); Mail_Message dsnMessage = DeliveryStatusNotification.CreateDsnMessage( session.From, variablesMgr.Process(messageTemplate.Subject), rtf, relayInfo.EnvelopeID, relayInfo.Date, null, (session.IsConnected && string.IsNullOrEmpty(session.LocalHostName)) ? session.LocalEndPoint.Address.ToString() : session.LocalHostName, relayInfo.OriginalRecipient, session.To, "failed", error, session.RemoteHostName, DateTime.Now, DateTime.MinValue, (relayInfo.DSN_Ret == SMTP_DSN_Ret.NotSpecified) ? SMTP_DSN_Ret.FullMessage : relayInfo.DSN_Ret, relayMessage ); using (MemoryStream strm = new MemoryStream()){ dsnMessage.ToStream(strm, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8); m_pVirtualServer.ProcessAndStoreMessage("", new string[] { session.From }, strm, null); } relayMessage.Dispose(); dsnMessage.Dispose(); } catch (Exception x) { LumiSoft.MailServer.Error.DumpError(m_pVirtualServer.Name, x); } }
/// <summary> /// Creates delivery status notifications(DSN) message. /// </summary> /// <param name="to">DSN message To.</param> /// <param name="subject">DSN message subject.</param> /// <param name="rtfText">DSN message RTF body text.</param> /// <param name="envelopeID">Envelope ID(MAIL FROM: ENVID).</param> /// <param name="arrivalDate">Message arrival date.</param> /// <param name="receivedFromMTA">The remote host EHLo name from where messages was received.</param> /// <param name="reportingMTA">Reporting MTA name.</param> /// <param name="originalRecipient">Original recipient(RCPT TO: ORCTP).</param> /// <param name="finalRecipient">Final recipient.</param> /// <param name="action">DSN action.</param> /// <param name="statusCode_text">Remote SMTP status code with text.</param> /// <param name="remoteMTA">Remote MTA what returned <b>statusCode_text</b>.</param> /// <param name="lastAttempt">Last delivery attempt.</param> /// <param name="retryUntil">Date time how long server will attempt to deliver message.</param> /// <param name="ret">Specifies what original message part are renturned.</param> /// <param name="message">Original message.</param> /// <returns>Returns created DSN message.</returns> public static Mail_Message CreateDsnMessage(string to, string subject, string rtfText, string envelopeID, DateTime arrivalDate, string receivedFromMTA, string reportingMTA, string originalRecipient, string finalRecipient, string action, string statusCode_text, string remoteMTA, DateTime lastAttempt, DateTime retryUntil, SMTP_DSN_Ret ret, Mail_Message message) { // For more info, see RFC 3464. // Ensure that all line-feeds are CRLF. rtfText = rtfText.Replace("\r\n", "\n").Replace("\n", "\r\n"); Mail_Message msg = new Mail_Message(); msg.MimeVersion = "1.0"; msg.Date = DateTime.Now; msg.From = new Mail_t_MailboxList(); msg.From.Add(new Mail_t_Mailbox("Mail Delivery Subsystem", "postmaster@local")); msg.To = new Mail_t_AddressList(); msg.To.Add(new Mail_t_Mailbox(null, to)); msg.Subject = subject; //--- multipart/report ------------------------------------------------------------------------------------------------- MIME_h_ContentType contentType_multipartReport = new MIME_h_ContentType(MIME_MediaTypes.Multipart.report); contentType_multipartReport.Parameters["report-type"] = "delivery-status"; contentType_multipartReport.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartReport multipartReport = new MIME_b_MultipartReport(contentType_multipartReport); msg.Body = multipartReport; //--- multipart/alternative ----------------------------------------------------------------------------------------- MIME_Entity entity_multipart_alternative = new MIME_Entity(); MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative); contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.'); MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative); entity_multipart_alternative.Body = multipartAlternative; multipartReport.BodyParts.Add(entity_multipart_alternative); //--- text/plain --------------------------------------------------------------------------------------------------- MIME_Entity entity_text_plain = new MIME_Entity(); MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain); entity_text_plain.Body = text_plain; text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, SCore.RtfToText(rtfText)); 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, SCore.RtfToHtml(rtfText)); multipartAlternative.BodyParts.Add(entity_text_html); //--- message/delivery-status MIME_Entity entity_message_deliveryStatus = new MIME_Entity(); MIME_b_Message body_message_deliveryStatus = new MIME_b_Message(MIME_MediaTypes.Message.delivery_status); entity_message_deliveryStatus.Body = body_message_deliveryStatus; StringBuilder dsnText = new StringBuilder(); if (!string.IsNullOrEmpty(envelopeID)) { dsnText.Append("Original-Envelope-Id: " + envelopeID + "\r\n"); } dsnText.Append("Arrival-Date: " + MIME_Utils.DateTimeToRfc2822(arrivalDate) + "\r\n"); if (!string.IsNullOrEmpty(receivedFromMTA)) { dsnText.Append("Received-From-MTA: dns; " + receivedFromMTA + "\r\n"); } dsnText.Append("Reporting-MTA: dns; " + reportingMTA + "\r\n"); dsnText.Append("\r\n"); if (!string.IsNullOrEmpty(originalRecipient)) { dsnText.Append("Original-Recipient: " + originalRecipient + "\r\n"); } dsnText.Append("Final-Recipient: rfc822;" + finalRecipient + "" + "\r\n"); dsnText.Append("Action: " + action + "\r\n"); dsnText.Append("Status: " + statusCode_text.Substring(0, 1) + ".0.0" + "\r\n"); if (!string.IsNullOrEmpty(statusCode_text)) { dsnText.Append("Diagnostic-Code: smtp; " + statusCode_text + "\r\n"); } if (!string.IsNullOrEmpty(remoteMTA)) { dsnText.Append("Remote-MTA: dns; " + remoteMTA + "\r\n"); } if (lastAttempt != DateTime.MinValue) { dsnText.Append("Last-Attempt-Date: " + MIME_Utils.DateTimeToRfc2822(lastAttempt) + "\r\n"); } if (retryUntil != DateTime.MinValue) { dsnText.Append("Will-Retry-Until: " + MIME_Utils.DateTimeToRfc2822(retryUntil) + "\r\n"); } dsnText.Append("\r\n"); body_message_deliveryStatus.SetData(new MemoryStream(Encoding.UTF8.GetBytes(dsnText.ToString())), MIME_TransferEncodings.EightBit); multipartReport.BodyParts.Add(entity_message_deliveryStatus); //--- message/rfc822 if (message != null) { MIME_Entity entity_message_rfc822 = new MIME_Entity(); MIME_b_MessageRfc822 body_message_rfc822 = new MIME_b_MessageRfc822(); entity_message_rfc822.Body = body_message_rfc822; if (ret == SMTP_DSN_Ret.FullMessage) { body_message_rfc822.Message = message; } else { MemoryStream ms = new MemoryStream(); message.Header.ToStream(ms, null, null); ms.Position = 0; body_message_rfc822.Message = Mail_Message.ParseFromStream(ms); } multipartReport.BodyParts.Add(entity_message_rfc822); } return(msg); }
public void LoadInfos() { if (!Client.IsConnected) { throw new EMailException { ExceptionType = EMAIL_EXCEPTION_TYPE.NOT_CONNECTED } } ; Client.Fetch( true, IMAP_t_SeqSet.Parse(UID), new IMAP_t_Fetch_i[] { new IMAP_t_Fetch_i_Rfc822() }, (sender, e) => { if (e.Value is IMAP_r_u_Fetch) { IMAP_r_u_Fetch fetchResp = (IMAP_r_u_Fetch)e.Value; try { if (fetchResp.Rfc822 != null) { fetchResp.Rfc822.Stream.Position = 0; Mail_Message mime = Mail_Message.ParseFromStream(fetchResp.Rfc822.Stream); fetchResp.Rfc822.Stream.Dispose(); if (String.IsNullOrWhiteSpace(mime.BodyText)) { _TextBody = mime.BodyHtmlText; } else { _TextBody = mime.BodyText; } Attachments.Clear(); foreach (MIME_Entity entity in mime.Attachments) { IMAP_Mail_Attachment att = new IMAP_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; Attachments.Add(att); } } } catch (Exception exe) { throw new EMailException { ExceptionType = EMAIL_EXCEPTION_TYPE.ERROR_ON_GET_MESSAGE, InnerException = exe }; } } } ); }
private void m_pImap_Fetch_MessageItems_UntaggedResponse(object sender, EventArgs <IMAP_r_u> e) { DataTable dtmail = null; switch (Defaut_Start.flagViewLast) { case Defaut_Start.ViewEtat.ViewReceive: dtmail = datalistmail.getInstance().getdt(); break; case Defaut_Start.ViewEtat.ViewSend: dtmail = datalistmail.getInstance().getdtSend(); break; case Defaut_Start.ViewEtat.ViewSuppr: break; case Defaut_Start.ViewEtat.ViewImport: break; case Defaut_Start.ViewEtat.ViewBrouillon: break; } try { var email = e.Value as IMAP_r_u_Fetch; if (dtmail.Select("mailID='@id'".Replace("@id", email.UID.UID.ToString())).Length < 1) { if (email.Rfc822 != null) { email.Rfc822.Stream.Position = 0; var mine = Mail_Message.ParseFromStream(email.Rfc822.Stream); email.Rfc822.Stream.Close(); DataRow dtr = dtmail.NewRow(); string msender = ((LumiSoft.Net.Mail.Mail_t_Mailbox)(email.Envelope.Sender[0])).DisplayName; string from = mine.From[0].Address; string subject = mine.Subject; string keyw = mine.Keywords; var mailCc = mine.Cc; var mailTo = mine.To; DateTime dateSent = mine.Date; string seen = email.Flags.Flags.ToString(); string body = ""; string bodys = ""; if (string.IsNullOrEmpty(mine.BodyHtmlText)) { if (!string.IsNullOrEmpty(mine.BodyText)) { body = bodys = mine.BodyText; } } else { body = mine.BodyHtmlText; } if (!string.IsNullOrEmpty(mine.BodyText)) { bodys = mine.BodyText; } string pathAttachmentFile = ""; string dir = "C:\\Users\\Sipcom-pc-info\\Documents\\Visual Studio 2012\\Projects\\Email_Test\\Email_Test\\attchment\\"; if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } if (mine.Attachments.Count() > 0) { var list = mine.Attachments.ToList(); foreach (var att in list) { var part = att.Body as MIME_b_SinglepartBase; string filename = dir + att.ContentType.Param_Name; FileInfo file = new FileInfo(filename); if (file.Exists) { file.Attributes = FileAttributes.Normal; file.Delete(); } File.WriteAllBytes(filename, part.Data); pathAttachmentFile = filename + ";" + pathAttachmentFile; } } string bodySimple = ""; if (bodys.Length >= 30) { bodySimple = bodys.Substring(0, 30); } else { bodySimple = bodys; } string listCc = ""; if (mailCc != null) { foreach (Mail_t_Mailbox address in mailCc.Mailboxes) { listCc = listCc + address.Address.ToString() + ";"; } } string listTo = ""; if (mailTo != null) { foreach (Mail_t_Mailbox address in mailTo.Mailboxes) { listTo = listTo + address.Address.ToString() + ";"; } } body = body.Replace(@"cid:", @"/attchment/"); dtr["mailID"] = email.UID.UID.ToString(); dtr["fk_userid"] = 1; dtr["mailsender"] = msender; dtr["mailfrom"] = from; dtr["mailto"] = listTo; dtr["mailcc"] = listCc; dtr["maildateTime"] = dateSent.ToString("yyyy-MM-dd HH:mm"); dtr["mailsubject"] = subject; dtr["mailbodySimple"] = bodySimple; dtr["mailbody"] = body; dtr["pathAttachmentFile"] = pathAttachmentFile; dtr["NotSeen"] = seen.Equals("\\Seen") ? 1 : 0; dtmail.Rows.Add(dtr); } } } catch (Exception ex) { Console.WriteLine("Handle-Err:" + ex.Message); } }
public override void Parse() { string linkText = string.Empty; string linkURL = string.Empty; try { byte[] fileByteArray = Utility.GetFileByteArray(FileUrl); if (fileByteArray != null) { using (MemoryStream fileStream = new MemoryStream(fileByteArray, false)) { Mail_Message mime = Mail_Message.ParseFromStream(fileStream); HtmlDocument doc = new HtmlDocument(); string html = string.IsNullOrEmpty(mime.BodyHtmlText) ? mime.BodyText : mime.BodyHtmlText; if (!string.IsNullOrEmpty(html)) { doc.LoadHtml(html); foreach (HtmlNode link in doc.DocumentNode.SelectNodesOrEmpty("//a[@href]")) { if (link.Attributes["href"].Value.StartsWith("#", StringComparison.InvariantCultureIgnoreCase) == false && link.Attributes["href"].Value.StartsWith("javascript:", StringComparison.InvariantCultureIgnoreCase) == false && link.Attributes["href"].Value.StartsWith("mailto:", StringComparison.InvariantCultureIgnoreCase) == false) { linkURL = link.Attributes["href"].Value; if (link.FirstChild == link.LastChild) { linkText = link.InnerText; } else { linkText = link.LastChild.InnerText; } linkText = new string(linkText.ToCharArray()).Replace("\r\n", " "); FileLink objLink = new FileLink() { ParentFileUrl = FileUrl, LinkText = linkText, LinkAddress = linkURL }; Results.Add(objLink); } } } } } } catch (Exception ex) { FileLink objLink = new FileLink() { ParentFileUrl = FileUrl, LinkText = "Error occurred when parsing this file.", LinkAddress = ex.Message, hasError = true }; Results.Add(objLink); } }
public GlobalMessageRuleActionResult DoActions(DataView dvActions, VirtualServer server, Stream message, string sender, string[] to) { bool deleteMessage = false; string storeFolder = null; string errorText = null; foreach (DataRowView dataRowView in dvActions) { GlobalMessageRuleActionType globalMessageRuleAction_enum = (GlobalMessageRuleActionType)dataRowView["ActionType"]; byte[] data = (byte[])dataRowView["ActionData"]; message.Position = 0L; if (globalMessageRuleAction_enum == (GlobalMessageRuleActionType)1) { XmlTable xmlTable = new XmlTable("ActionData"); xmlTable.Parse(data); string value = xmlTable.GetValue("From"); string value2 = xmlTable.GetValue("Message"); MIME_h_Collection mIME_h_Collection = new MIME_h_Collection(new MIME_h_Provider()); mIME_h_Collection.Parse(new SmartStream(message, false)); if (!mIME_h_Collection.Contains("X-LS-MailServer-AutoResponse")) { Mail_Message mail_Message = Mail_Message.ParseFromByte(Encoding.UTF8.GetBytes(value2)); mail_Message.Header.Add(new MIME_h_Unstructured("X-LS-MailServer-AutoResponse", "")); mail_Message.Date = DateTime.Now; if (mail_Message.To == null || mail_Message.To.Count == 0) { if (mail_Message.To == null) { mail_Message.To = new Mail_t_AddressList { new Mail_t_Mailbox(null, sender) }; } else { mail_Message.To.Add(new Mail_t_Mailbox(null, sender)); } } if (mail_Message.Subject != null && mIME_h_Collection.Contains("Subject")) { mail_Message.Subject = mail_Message.Subject.Replace("#SUBJECT", mIME_h_Collection.GetFirst("Subject").ValueToString().Trim()); } if (!string.IsNullOrEmpty(sender)) { server.ProcessAndStoreMessage(value, new string[] { sender }, new MemoryStream(mail_Message.ToByte(new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8)), null); } } } else if (globalMessageRuleAction_enum == GlobalMessageRuleActionType.DeleteMessage) { XmlTable xmlTable2 = new XmlTable("ActionData"); xmlTable2.Parse(data); deleteMessage = true; } else if (globalMessageRuleAction_enum == GlobalMessageRuleActionType.ExecuteProgram) { XmlTable xmlTable3 = new XmlTable("ActionData"); xmlTable3.Parse(data); Process.Start(new ProcessStartInfo { FileName = xmlTable3.GetValue("Program"), Arguments = xmlTable3.GetValue("Arguments"), CreateNoWindow = true }); } else if (globalMessageRuleAction_enum == GlobalMessageRuleActionType.ForwardToEmail) { XmlTable xmlTable4 = new XmlTable("ActionData"); xmlTable4.Parse(data); MIME_h_Collection mIME_h_Collection2 = new MIME_h_Collection(new MIME_h_Provider()); mIME_h_Collection2.Parse(new SmartStream(message, false)); bool flag = false; if (mIME_h_Collection2.Contains("X-LS-MailServer-ForwardedTo")) { MIME_h[] array = mIME_h_Collection2["X-LS-MailServer-ForwardedTo"]; for (int i = 0; i < array.Length; i++) { MIME_h mIME_h = array[i]; if (mIME_h.ValueToString().Trim() == xmlTable4.GetValue("Email")) { flag = true; break; } } } message.Position = 0L; if (!flag) { MemoryStream memoryStream = new MemoryStream(); byte[] bytes = Encoding.UTF8.GetBytes("X-LS-MailServer-ForwardedTo: " + xmlTable4.GetValue("Email") + "\r\n"); memoryStream.Write(bytes, 0, bytes.Length); SCore.StreamCopy(message, memoryStream); server.ProcessAndStoreMessage(sender, new string[] { xmlTable4.GetValue("Email") }, memoryStream, null); } } else if (globalMessageRuleAction_enum == GlobalMessageRuleActionType.ForwardToHost) { XmlTable xmlTable5 = new XmlTable("ActionData"); xmlTable5.Parse(data); for (int j = 0; j < to.Length; j++) { string to2 = to[j]; message.Position = 0L; server.RelayServer.StoreRelayMessage(Guid.NewGuid().ToString(), null, message, HostEndPoint.Parse(xmlTable5.GetValue("Host") + ":" + xmlTable5.GetValue("Port")), sender, to2, null, SMTP_DSN_Notify.NotSpecified, SMTP_DSN_Ret.NotSpecified); } message.Position = 0L; } else { if (globalMessageRuleAction_enum == GlobalMessageRuleActionType.StoreToDiskFolder) { XmlTable xmlTable6 = new XmlTable("ActionData"); xmlTable6.Parse(data); string text = xmlTable6.GetValue("Folder"); if (!text.EndsWith("\\")) { text += "\\"; } if (!Directory.Exists(text)) { continue; } using (FileStream fileStream = File.Create(string.Concat(new string[] { text, DateTime.Now.ToString("ddMMyyyyHHmmss"), "_", Guid.NewGuid().ToString().Replace('-', '_').Substring(0, 8), ".eml" }))) { SCore.StreamCopy(message, fileStream); continue; } } if (globalMessageRuleAction_enum == GlobalMessageRuleActionType.StoreToIMAPFolder) { XmlTable xmlTable7 = new XmlTable("ActionData"); xmlTable7.Parse(data); storeFolder = xmlTable7.GetValue("Folder"); } else if (globalMessageRuleAction_enum == (GlobalMessageRuleActionType)8) { XmlTable xmlTable8 = new XmlTable("ActionData"); xmlTable8.Parse(data); Mail_Message mail_Message2 = Mail_Message.ParseFromStream(message); mail_Message2.Header.Add(new MIME_h_Unstructured(xmlTable8.GetValue("HeaderFieldName"), xmlTable8.GetValue("HeaderFieldValue"))); message.SetLength(0L); mail_Message2.ToStream(message, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8); } else if (globalMessageRuleAction_enum == (GlobalMessageRuleActionType)9) { XmlTable xmlTable9 = new XmlTable("ActionData"); xmlTable9.Parse(data); Mail_Message mail_Message3 = Mail_Message.ParseFromStream(message); mail_Message3.Header.RemoveAll(xmlTable9.GetValue("HeaderFieldName")); message.SetLength(0L); mail_Message3.ToStream(message, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8); } else if (globalMessageRuleAction_enum == (GlobalMessageRuleActionType)10) { XmlTable xmlTable10 = new XmlTable("ActionData"); xmlTable10.Parse(data); errorText = xmlTable10.GetValue("ErrorText"); } else if (globalMessageRuleAction_enum == (GlobalMessageRuleActionType)11) { XmlTable xmlTable11 = new XmlTable("ActionData"); xmlTable11.Parse(data); new _MessageRuleAction_FTP_AsyncSend(xmlTable11.GetValue("Server"), Convert.ToInt32(xmlTable11.GetValue("Port")), xmlTable11.GetValue("User"), xmlTable11.GetValue("Password"), xmlTable11.GetValue("Folder"), message, DateTime.Now.ToString("ddMMyyyyHHmmss") + "_" + Guid.NewGuid().ToString().Replace('-', '_').Substring(0, 8) + ".eml"); } else if (globalMessageRuleAction_enum == (GlobalMessageRuleActionType)12) { XmlTable xmlTable12 = new XmlTable("ActionData"); xmlTable12.Parse(data); Mail_Message mail_Message4 = Mail_Message.ParseFromStream(message); if (!mail_Message4.Header.Contains("Newsgroups:")) { mail_Message4.Header.Add(new MIME_h_Unstructured("Newsgroups:", xmlTable12.GetValue("Newsgroup"))); } new _MessageRuleAction_NNTP_Async(xmlTable12.GetValue("Server"), Convert.ToInt32(xmlTable12.GetValue("Port")), xmlTable12.GetValue("Newsgroup"), new MemoryStream(mail_Message4.ToByte(new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8))); } else if (globalMessageRuleAction_enum == (GlobalMessageRuleActionType)13) { XmlTable xmlTable13 = new XmlTable("ActionData"); xmlTable13.Parse(data); new _MessageRuleAction_HTTP_Async(xmlTable13.GetValue("URL"), message); } } } return(new GlobalMessageRuleActionResult(deleteMessage, storeFolder, errorText)); }
/// <summary> /// This method is called when FETCH RFC822 untagged response is received. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pImap_Fetch_Message_UntaggedResponse(object sender, EventArgs <IMAP_r_u> e) { /* NOTE: All IMAP untagged responses may be raised from thread pool thread, * so all UI operations must use Invoke. * * There may be other untagged responses than FETCH, because IMAP server * may send any untagged response to any command. */ try { if (e.Value is IMAP_r_u_Fetch) { IMAP_r_u_Fetch fetchResp = (IMAP_r_u_Fetch)e.Value; try { fetchResp.Rfc822.Stream.Position = 0; Mail_Message mime = Mail_Message.ParseFromStream(fetchResp.Rfc822.Stream); fetchResp.Rfc822.Stream.Dispose(); /* * m_pTabPageMail_MessagesToolbar.Items["save"].Enabled = true; * m_pTabPageMail_MessagesToolbar.Items["delete"].Enabled = true; * * m_pTabPageMail_MessageAttachments.Tag = mime; * 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.ImageIndex = 0; * item.Tag = entity; * m_pTabPageMail_MessageAttachments.Items.Add(item); * }*/ if (mime.Subject != null) { currentEmail.subject = mime.Subject; currentEmail.message = mime.BodyHtmlText; currentEmail.from = mime.From.ToString(); currentEmail.date = mime.Date.ToShortDateString(); currentEmail.to = mime.To.ToString(); } } catch (Exception x) { Console.WriteLine("Error: " + x.ToString(), "Error:"); } } } catch (Exception x) { Console.WriteLine("Error: " + x.ToString(), "Error:"); } }