Esempio n. 1
0
 private string ReplaceVariable(string variable)
 {
     try
     {
         if (variable.StartsWith("<#sys.datetime"))
         {
             string result = DateTime.Now.ToString(TextUtils.UnQuoteString(variable.Substring(variable.IndexOf("(") + 1, variable.IndexOf(")") - variable.IndexOf("(") - 1)));
             return(result);
         }
         if (variable == "<#relay.hostname>")
         {
             string result = Dns.GetHostName();
             return(result);
         }
         if (variable == "<#relay.undelivered_after>")
         {
             string result = Convert.ToString(this.m_pRelayServer.UndeliveredAfter / 60);
             return(result);
         }
         if (variable == "<#relay.error>")
         {
             string result = this.m_ErrorText;
             return(result);
         }
         if (variable == "<#relay.session_id>")
         {
             string result = this.m_pRelaySession.ID;
             return(result);
         }
         if (variable == "<#relay.session_messageid>")
         {
             string result = this.m_pRelaySession.MessageID;
             return(result);
         }
         if (variable == "<#relay.session_hostname>")
         {
             try
             {
                 string result = Dns.GetHostEntry(this.m_pRelaySession.RemoteEndPoint.Address).HostName;
                 return(result);
             }
             catch
             {
                 string result = this.m_pRelaySession.RemoteEndPoint.Address.ToString();
                 return(result);
             }
         }
         if (variable == "<#relay.to>")
         {
             string result = this.m_pRelaySession.To;
             return(result);
         }
         if (variable == "<#relay.from>")
         {
             string result = this.m_pRelaySession.From;
             return(result);
         }
         if (variable == "<#message.bodytext>")
         {
             string bodyText = this.m_pMime.BodyText;
             if (bodyText != null)
             {
                 string result = bodyText;
                 return(result);
             }
         }
         else if (variable.StartsWith("<#message.header"))
         {
             string text = TextUtils.UnQuoteString(variable.Substring(variable.IndexOf("[") + 1, variable.IndexOf("]") - variable.IndexOf("[") - 1)).Trim();
             if (text.EndsWith(":"))
             {
                 text = text.Substring(0, text.Length - 1);
             }
             MIME_h first = this.m_pMime.Header.GetFirst(text);
             if (first != null)
             {
                 string result = first.ToString().Split(new char[]
                 {
                     ':'
                 }, 2)[1].Trim();
                 return(result);
             }
         }
     }
     catch
     {
         string result = variable;
         return(result);
     }
     return("");
 }
        /// <summary>
        /// Gets if specified message matches with this class search-key.
        /// </summary>
        /// <param name="no">IMAP message sequence number.</param>
        /// <param name="uid">IMAP message UID.</param>
        /// <param name="size">IMAP message size in bytes.</param>
        /// <param name="internalDate">IMAP message INTERNALDATE (dateTime when server stored message).</param>
        /// <param name="flags">IMAP message flags.</param>
        /// <param name="message">Mime message main header only.</param>
        /// <param name="bodyText">Message body text.</param>
        /// <returns></returns>
        public bool Match(long no, long uid, long size, DateTime internalDate, IMAP_MessageFlags flags, Mail_Message message, string bodyText)
        {
            #region ALL

            // ALL
            //		All messages in the mailbox; the default initial key for ANDing.
            if (m_SearchKeyName == "ALL")
            {
                return(true);
            }

            #endregion

            #region BEFORE

            // BEFORE <date>
            //	Messages whose internal date (disregarding time and timezone)
            //	is earlier than the specified date.
            else if (m_SearchKeyName == "BEFORE")
            {
                if (internalDate.Date < (DateTime)m_SearchKeyValue)
                {
                    return(true);
                }
            }

            #endregion

            #region BODY

            // BODY <string>
            //	Messages that contain the specified string in the body of the message.
            //
            //	NOTE: Compare must be done on decoded header and decoded body of message.
            //		  In all search keys that use strings, a message matches the key if
            //		  the string is a substring of the field.  The matching is case-insensitive.
            else if (m_SearchKeyName == "BODY")
            {
                string val = bodyText;
                if (val != null && val.ToLower().IndexOf(((string)m_SearchKeyValue).ToLower()) > -1)
                {
                    return(true);
                }
            }

            #endregion

            #region HEADER

            // HEADER <field-name> <string>
            //	Messages that have a header with the specified field-name (as
            //	defined in [RFC-2822]) and that contains the specified string
            //	in the text of the header (what comes after the colon).  If the
            //	string to search is zero-length, this matches all messages that
            //	have a header line with the specified field-name regardless of
            //	the contents.
            //
            //	NOTE: Compare must be done on decoded header field value.
            //		  In all search keys that use strings, a message matches the key if
            //		  the string is a substring of the field.  The matching is case-insensitive.
            else if (m_SearchKeyName == "HEADER")
            {
                string[] headerField_value = (string[])m_SearchKeyValue;

                // If header field ends with ":", remove it.
                if (headerField_value[0].EndsWith(":"))
                {
                    headerField_value[0] = headerField_value[0].Substring(0, headerField_value[0].Length - 1);
                }

                if (string.IsNullOrEmpty(headerField_value[1]))
                {
                    return(true);
                }
                else
                {
                    MIME_h h = message.Header.GetFirst(headerField_value[0]);
                    if (h == null)
                    {
                        return(false);
                    }
                    else
                    {
                        if (h.ValueToString().ToLower().IndexOf(headerField_value[1].ToLower()) > -1)
                        {
                            return(true);
                        }
                    }
                }
            }

            #endregion

            #region KEYWORD

            // KEYWORD <flag>
            //	Messages with the specified keyword flag set.
            else if (m_SearchKeyName == "KEYWORD")
            {
                if ((flags & IMAP_Utils.ParseMessageFlags((string)m_SearchKeyValue)) != 0)
                {
                    return(true);
                }
            }

            #endregion

            #region LARGER

            // LARGER <n>
            //	Messages with an [RFC-2822] size larger than the specified number of octets.
            else if (m_SearchKeyName == "LARGER")
            {
                if (size > (long)m_SearchKeyValue)
                {
                    return(true);
                }
            }

            #endregion

            #region NOT

            //	NOT <search-key> or (<search-key> <search-key> ...)(SearchGroup)
            //		Messages that do not match the specified search key.
            else if (m_SearchKeyName == "NOT")
            {
                return(!SearchGroup.Match_Key_Value(m_SearchKeyValue, no, uid, size, internalDate, flags, message, bodyText));
            }

            #endregion

            #region ON

            // ON <date>
            //	Messages whose internal date (disregarding time and timezone)
            //	is within the specified date.
            else if (m_SearchKeyName == "ON")
            {
                if (internalDate.Date == (DateTime)m_SearchKeyValue)
                {
                    return(true);
                }
            }

            #endregion

            #region OR

            //	OR <search-key1> <search-key2> - SearckKey can be parenthesis list of keys !
            //		Messages that match either search key.
            else if (m_SearchKeyName == "OR")
            {
                object serachKey1 = ((object[])m_SearchKeyValue)[0];
                object serachKey2 = ((object[])m_SearchKeyValue)[1];

                if (SearchGroup.Match_Key_Value(serachKey1, no, uid, size, internalDate, flags, message, bodyText) || SearchGroup.Match_Key_Value(serachKey2, no, uid, size, internalDate, flags, message, bodyText))
                {
                    return(true);
                }
            }

            #endregion

            #region SENTBEFORE

            // SENTBEFORE <date>
            //	Messages whose [RFC-2822] Date: header (disregarding time and
            //	timezone) is earlier than the specified date.
            else if (m_SearchKeyName == "SENTBEFORE")
            {
                if (message.Date.Date < (DateTime)m_SearchKeyValue)
                {
                    return(true);
                }
            }

            #endregion

            #region SENTON

            // SENTON <date>
            //	Messages whose [RFC-2822] Date: header (disregarding time and
            //	timezone) is within the specified date.
            else if (m_SearchKeyName == "SENTON")
            {
                if (message.Date.Date == (DateTime)m_SearchKeyValue)
                {
                    return(true);
                }
            }

            #endregion

            #region SENTSINCE

            // SENTSINCE <date>
            //	Messages whose [RFC-2822] Date: header (disregarding time and
            //	timezone) is within or later than the specified date.
            else if (m_SearchKeyName == "SENTSINCE")
            {
                if (message.Date.Date >= (DateTime)m_SearchKeyValue)
                {
                    return(true);
                }
            }

            #endregion

            #region SINCE

            // SINCE <date>
            //	Messages whose internal date (disregarding time and timezone)
            //	is within or later than the specified date.
            else if (m_SearchKeyName == "SINCE")
            {
                if (internalDate.Date >= (DateTime)m_SearchKeyValue)
                {
                    return(true);
                }
            }

            #endregion

            #region SMALLER

            // SMALLER <n>
            //	Messages with an [RFC-2822] size smaller than the specified	number of octets.
            else if (m_SearchKeyName == "SMALLER")
            {
                if (size < (long)m_SearchKeyValue)
                {
                    return(true);
                }
            }

            #endregion

            #region TEXT

            // TEXT <string>
            //	Messages that contain the specified string in the header or	body of the message.
            //
            //  NOTE: Compare must be done on decoded header and decoded body of message.
            //		  In all search keys that use strings, a message matches the key if
            //		  the string is a substring of the field.  The matching is case-insensitive.
            else if (m_SearchKeyName == "TEXT")
            {
                // See body first
                string val = bodyText;
                if (val != null && val.ToLower().IndexOf(((string)m_SearchKeyValue).ToLower()) > -1)
                {
                    return(true);
                }

                // If we reach so far, that means body won't contain specified text and we need to check header.
                foreach (MIME_h headerField in message.Header)
                {
                    if (headerField.ToString().ToLower().IndexOf(((string)m_SearchKeyValue).ToLower()) > -1)
                    {
                        return(true);
                    }
                }
            }

            #endregion

            #region UID

            // UID <sequence set>
            //	Messages with unique identifiers corresponding to the specified
            //	unique identifier set.  Sequence set ranges are permitted.
            else if (m_SearchKeyName == "UID")
            {
                return(((IMAP_SequenceSet)m_SearchKeyValue).Contains(uid));
            }

            #endregion

            #region UNKEYWORD

            // UNKEYWORD <flag>
            //	Messages that do not have the specified keyword flag set.
            else if (m_SearchKeyName == "UNKEYWORD")
            {
                if ((flags & IMAP_Utils.ParseMessageFlags((string)m_SearchKeyValue)) == 0)
                {
                    return(true);
                }
            }

            #endregion

            #region SEQUENCESET

            // <sequence set>
            //		Messages with message sequence numbers corresponding to the
            //		specified message sequence number set.
            else if (m_SearchKeyName == "SEQUENCESET")
            {
                return(((IMAP_SequenceSet)m_SearchKeyValue).Contains(no));
            }

            #endregion

            return(false);
        }
        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));
        }
Esempio n. 4
0
        /// <summary>
        /// Replaces specified variable with actual value.
        /// </summary>
        /// <param name="variable">Variable to replace.</param>
        private string ReplaceVariable(string variable)
        {
            try
            {
                // Current date time. Syntax: <#sys.datetime("format")>
                if (variable.StartsWith("<#sys.datetime"))
                {
                    return(DateTime.Now.ToString(TextUtils.UnQuoteString(variable.Substring(variable.IndexOf("(") + 1, variable.IndexOf(")") - variable.IndexOf("(") - 1))));
                }

                // Relay server host name.
                else if (variable == "<#relay.hostname>")
                {
                    return(System.Net.Dns.GetHostName());
                }
                // Specifies after how many hours server will try to deliver message.
                else if (variable == "<#relay.undelivered_after>")
                {
                    return(Convert.ToString(m_pRelayServer.UndeliveredAfter / 60));
                }
                // Error why relay failed.
                else if (variable == "<#relay.error>")
                {
                    return(m_ErrorText);
                }
                // Relay session ID.
                else if (variable == "<#relay.session_id>")
                {
                    return(m_pRelaySession.ID);
                }
                // Relay session message ID.
                else if (variable == "<#relay.session_messageid>")
                {
                    return(m_pRelaySession.MessageID);
                }
                // Relay session connected host name.
                else if (variable == "<#relay.session_hostname>")
                {
                    try
                    {
                        return(System.Net.Dns.GetHostEntry(m_pRelaySession.RemoteEndPoint.Address).HostName);
                    }
                    catch
                    {
                        return(m_pRelaySession.RemoteEndPoint.Address.ToString());
                    }
                }

                /*
                 * // Relay session active(last) log part.
                 * else if(variable == "<#relay.session_activelog>"){
                 *  if(m_pRelaySession.SessionActiveLog != null){
                 *      return m_pRelaySession.SessionActiveLog.ToString();
                 *  }
                 *  else{
                 *      return "<Relay Logging disabled>";
                 *  }
                 * }*/
                // Relay message destination recipient email address.
                else if (variable == "<#relay.to>")
                {
                    return(m_pRelaySession.To);
                }
                // Original sender email address.
                else if (variable == "<#relay.from>")
                {
                    return(m_pRelaySession.From);
                }

                // Message body text.
                else if (variable == "<#message.bodytext>")
                {
                    string bodyText = m_pMime.BodyText;
                    if (bodyText != null)
                    {
                        return(bodyText);
                    }
                }
                // Message header field value. Synatx: <#message.header["headerFieldName:"]>
                else if (variable.StartsWith("<#message.header"))
                {
                    string headerName = TextUtils.UnQuoteString(variable.Substring(variable.IndexOf("[") + 1, variable.IndexOf("]") - variable.IndexOf("[") - 1)).Trim();
                    if (headerName.EndsWith(":"))
                    {
                        headerName = headerName.Substring(0, headerName.Length - 1);
                    }
                    MIME_h headerField = m_pMime.Header.GetFirst(headerName);
                    if (headerField != null)
                    {
                        return(headerField.ToString().Split(new char[] { ':' }, 2)[1].Trim());
                    }
                }
            }
            catch
            {
                // Failed to replace variable value, just invaild synatx or who knows ... .
                // Just leave variable as is.
                return(variable);
            }

            return("");
        }