/// <summary> /// Stores MIME entity body to the specified stream. /// </summary> /// <param name="stream">Stream where to store body data.</param> /// <param name="headerWordEncoder">Header 8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="headerParmetersCharset">Charset to use to encode 8-bit header parameters. Value null means parameters not encoded.</param> /// <param name="headerReencode">If true always specified encoding is used for header. If false and header field value not modified, /// original encoding is kept.</param> /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception> internal protected override void ToStream(Stream stream, MIME_Encoding_EncodedWord headerWordEncoder, Encoding headerParmetersCharset, bool headerReencode) { if (stream == null) { throw new ArgumentNullException("stream"); } m_pMessage.ToStream(stream, headerWordEncoder, headerParmetersCharset, headerReencode); }
public void SendEmail(Mail mail, Setting setting) { Mail_Message message = new Mail_Message() { From = new Mail_t_MailboxList(), Subject = mail.Subject, //增加主题 Priority = mail.Priority.ToString(), //设置优先级 MessageID = MIME_Utils.CreateMessageID(), Date = mail.CreatedDateTime }; //增加发件人地址 message.From.Add(new Mail_t_Mailbox(null, mail.From)); //增加收件人地址 mail.To.ForEach(address => message.To.Add(new Mail_t_Mailbox(address, address))); //增加邮件内容 MIME_Entity.CreateEntity_Text_Html("Base64", Encoding.Default, mail.Body); //增加附件 if (mail.Attachments != null && mail.Attachments.Count > 0) { mail.Attachments.ForEach(attachment => { MIME_Entity.CreateEntity_Attachment(attachment.Name); }); } using (SMTP_Client smtpClient = new SMTP_Client()) { //设置SMPT服务地址和端口并连接 smtpClient.Connect(setting.SmtpHostName, setting.SmtpPort); //设置Authentication smtpClient.Auth(new LumiSoft.Net.AUTH.AUTH_SASL_Client_Login(setting.User.UserName, setting.User.Password)); using (MemoryStream stream = new MemoryStream()) { message.ToStream(stream); stream.Position = 0; //发送邮件 smtpClient.SendMessage(stream); } } }
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); } }
public static bool SendMail(string Body, string Title, string reciveEmail) { bool sended = false; using (SMTP_Client client = new SMTP_Client()) { try { //与Pop3服务器建立连接 client.Connect(smtp, port, false); client.EhloHelo(smtp); //验证身份 var authhh = new AUTH_SASL_Client_Plain(sendEmail, sendPassword); client.Auth(authhh); client.MailFrom(sendEmail, -1); //收件人列表 client.RcptTo(reciveEmail); //采用Mail_Message类型的Stream Mail_Message m = Create_PlainText_Html_Attachment_Image(reciveEmail, sendEmail, sendEmail, Title, Body); using (MemoryStream stream = new MemoryStream()) { m.ToStream(stream, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8); stream.Position = 0; client.SendMessage(stream); sended = true; } if (m != null) { m.Dispose(); } client.Disconnect(); client.Dispose(); } catch { return(false); } } return(sended); }
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); } }
/// <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); } }
private Boolean SendMailNew(bool isAsync, object userState) { string[] mailTos = mMailTo; string[] mailCcs = mMailCc; string[] mailBccs = mMailBcc; Dictionary <string, string> attachments = mMailAttachments; var toList = new Dictionary <string, string>(); foreach (var to in MailTo) { toList.Add(to, to); } var musername = mSMTPUsername; if (mSMTPUsername != null && mSMTPUsername.IndexOf("@") >= 0) { musername = mSMTPUsername.Substring(0, mSMTPUsername.IndexOf("@")); } bool checkspmail = CheckSpecialMail(toList); if (!checkspmail && MailCc != null) { checkspmail = CheckSpecialMail(MailCc); } if (checkspmail) { foreach (string address in toList.Keys) { using (SMTP_Client client = new SMTP_Client()) { client.Timeout = this.Timeout; client.Connect(mSMTPServer, mSMTPPort); client.EhloHelo(mSMTPServer); client.Authenticate(musername, mSMTPPassword); client.MailFrom(mMailFrom, -1); client.RcptTo(address); Mail_Message m = Create_PlainText_Html_Attachment_Image(toList, new Dictionary <string, string>() , mMailFrom, mMailFrom, MailSubject, mMailBody, attachments, "", "", CheckSpecialMail(new string[] { address })); try { using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { m.ToStream(stream, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8); stream.Position = 0; client.SendMessage(stream); } } catch (Exception ex) { throw ex; } if (m != null) { m.Dispose(); } client.Disconnect(); } } return(true); } else { using (SMTP_Client client = new SMTP_Client()) { client.Timeout = this.Timeout; client.Connect(mSMTPServer, mSMTPPort); client.EhloHelo(mSMTPServer); AUTH_SASL_Client authhh = client.AuthGetStrongestMethod(musername, mSMTPPassword); client.Auth(authhh); client.MailFrom(mMailFrom, -1); foreach (string address in toList.Keys) { client.RcptTo(address); } Mail_Message m = Create_PlainText_Html_Attachment_Image(toList, new Dictionary <string, string>() , mMailFrom, mMailFrom, MailSubject, mMailBody, attachments, "", "", false); try { using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { m.ToStream(stream, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8); stream.Position = 0; client.SendMessage(stream); } return(true); } catch (Exception ex) { throw ex; } finally { if (m != null) { m.Dispose(); } client.Disconnect(); } } } }
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)); }
public void Send(ChannelMessage message) { var creds = CredentialsProvider.GetCredentials().ToNetworkCredential(); Mail_Message msg = new Mail_Message(); msg.MimeVersion = "1.0"; msg.MessageID = MIME_Utils.CreateMessageID(); msg.Subject = message.Context; msg.From = message.From.ToMailBoxList(); msg.ReplyTo = message.ReturnTo == null? message.From.ToAddressList() : message.ReturnTo.ToAddressList(); if (String.IsNullOrEmpty(message.InReplyTo) == false) { msg.InReplyTo = message.InReplyTo; } msg.To = new Mail_t_AddressList(); foreach (var address in message.To) { msg.To.Add(address.ToMailBox()); } msg.Cc = new Mail_t_AddressList(); foreach (var address in message.CC) { msg.Cc.Add(address.ToMailBox()); } //--- 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; // Add text body if there is any if (message.BodyText != null && message.BodyText.Length > 0) { var bodyText = message.BodyText.ReadString(); // Make sure there is a newline at the end of our text, otherwise it will screw up // our multipart data format if (!bodyText.EndsWith(Environment.NewLine)) { bodyText = bodyText + Environment.NewLine; } text_plain.SetText(MIME_TransferEncodings.SevenBit, Encoding.UTF8, bodyText); } 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; if (message.BodyHtml != null && message.BodyHtml.Length > 0) { var bodyHtml = message.BodyHtml.ReadString(); // Make sure there is a newline at the end of our text, otherwise it will screw up // our multipart data format if (!bodyHtml.EndsWith(Environment.NewLine)) { bodyHtml = bodyHtml + Environment.NewLine; } text_html.SetText(MIME_TransferEncodings.SevenBit, Encoding.UTF8, bodyHtml); } multipartAlternative.BodyParts.Add(entity_text_html); foreach (var channelAttachment in message.Attachments) { MIME_b_Application attachmentBody = new MIME_b_Application(MIME_MediaTypes.Application.octet_stream); MIME_Entity attachment = new MIME_Entity(); attachment.Body = attachmentBody; // Has to happen before the following lines of code multipartMixed.BodyParts.Add(attachment); attachment.ContentType = new MIME_h_ContentType(MimeHelper.GetMimeType(channelAttachment.Filename)); attachment.ContentType.Param_Name = channelAttachment.Filename; MIME_h_ContentDisposition contentDisposition = new MIME_h_ContentDisposition(DispositionTypeNames.Attachment); contentDisposition.Param_FileName = channelAttachment.Filename; attachment.ContentDisposition = contentDisposition; attachment.ContentTransferEncoding = TransferEncoding.Base64.ToString(); attachmentBody.SetData(channelAttachment.ContentStream, MIME_TransferEncodings.Base64); } // Inject headers if (!String.IsNullOrEmpty(message.MessageIdentifier)) { msg.Header.Add(new MIME_h_Unstructured("x-i2mp-messageid", message.MessageIdentifier)); } //if (!String.IsNullOrEmpty(message.Metadata.i2mpFlow)) // msg.Header.Add(new MIME_h_Unstructured("x-i2mp-flow", message.Metadata.i2mpFlow)); //if (!String.IsNullOrEmpty(message.Metadata.i2mpReference)) // mailMessage.Headers.Add("X-i2mp-ref", message.Metadata.i2mpReference); //if (!String.IsNullOrEmpty(message.Metadata.i2mpSequence)) // mailMessage.Headers.Add("X-i2mp-seq", message.Metadata.i2mpSequence); //if (!String.IsNullOrEmpty(message.Metadata.i2mpRelation)) // mailMessage.Headers.Add("X-i2mp-rel", message.Metadata.i2mpRelation); //if (!String.IsNullOrEmpty(message.Metadata.i2mpRelationId)) // mailMessage.Headers.Add("X-i2mp-rel-id", message.Metadata.i2mpRelationId); // Send message try { SMTP_Client client = new SMTP_Client(); if ("/Settings/Channels/LoggerEnabled".AsKey(false)) { client.Logger = new LumiSoft.Net.Log.Logger(); } // todo push this logic into the smtp client implementation itself if (Hostname == "smtp.live.com") { // Hack for hotmail, first do a connect with no secured channel, // then a STARTTLS client.Connect(Hostname, Port, false); client.StartTLS(); } else { client.Connect(Hostname, Port, IsSecured); } client.Authenticate(creds.UserName, creds.Password); using (MemoryStream ms = new MemoryStream()) { client.MailFrom(msg.From[0].Address, -1); msg.ToStream(ms, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8); // Reset stream ms.Seek(0, SeekOrigin.Begin); foreach (var address in message.To) { client.RcptTo(address.Address); } foreach (var address in message.CC) { client.RcptTo(address.Address); } foreach (var address in message.BCC) { client.RcptTo(address.Address); } try { client.SendMessage(ms); } finally { client.Dispose(); } } } catch (SmtpFailedRecipientsException e) { throw new ChannelFunctionalException(e.Message, e) { DoNotRetry = true }; } catch (SmtpException e) { throw new ChannelFunctionalException(e.Message, e); } catch (Exception e) { throw new ChannelFunctionalException(e.Message, e); } }