Пример #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OutputMessageCreator"/> class.
 /// </summary>
 /// <param name="Msg">The MSG.</param>
 /// <param name="IncidentId">The incident id.</param>
 /// <param name="From">From.</param>
 public OutputMessageCreator(Pop3Message Msg, int IncidentId, string MailFrom, string From)
 {
     _sourceMsg = Msg;
     _from = From;
     _mailFrom = MailFrom;
     _incidentId = IncidentId;
 }
Пример #2
0
        /// <summary>
        /// Adds to incident message.
        /// </summary>
        /// <param name="IsInternal">if set to <c>true</c> [is internal].</param>
        /// <param name="IncidentId">The incident id.</param>
        /// <param name="EMailMessageId">The E mail message id.</param>
        /// <param name="msg">The MSG.</param>
        /// <returns></returns>
        public static int AddToIncidentMessage(bool IsInternal, int IncidentId, int EMailMessageId, Pop3Message msg)
        {
            IncidentBox incidentBox = IncidentBox.Load(Incident.GetIncidentBox(IncidentId));

            if (IsInternal)
            {
                // 2007-02-15: OZ: New Messagew Addon
                Issue2.SetNewMessage(IncidentId, false);
                //

                // TODO: If Responsible is Group, set current user as responsible

                return AddInternalEMail2Incident(IncidentId, EMailMessageId, EMailMessage.GetSenderName(msg), EMailMessage.GetSenderEmail(msg));
            }
            else
            {
                // 2007-02-15: OZ: New Messagew Addon
                Issue2.SetNewMessage(IncidentId, true);
                //

                return AddExternalEMail2Incident(IncidentId, EMailMessageId, EMailMessage.GetSenderName(msg), EMailMessage.GetSenderEmail(msg));
            }
        }
Пример #3
0
        public static ArrayList Send(int IncidentId, EMailRouterPop3Box pop3Box, Pop3Message InMsg, string[] RecipientEmails)
        {
            ArrayList retVal = new ArrayList();

            IncidentBox incidentBox = IncidentBox.Load( Incident.GetIncidentBox(IncidentId));

            EMailRouterIncidentBoxBlock settings = IncidentBoxDocument.Load(incidentBox.IncidentBoxId).EMailRouterBlock;

            if(pop3Box.IsInternal)
            {
                #region Internal -> Extrenal
                // Internal -> Internal Info

                // 2009-06-16 OZ: Add Chech send emails to internal users
                if (settings.AllowEMailRouting)
                {
                    // 2007-02-12 OZ: "FN LN" <*****@*****.**>
                    string FromEmail = string.Format("\"{0} {1}\" <{2}>",
                        Security.CurrentUser.LastName,
                        Security.CurrentUser.FirstName,
                        pop3Box.EMailAddress);

                    OutputMessageCreator output2Iternal = new OutputMessageCreator(InMsg, IncidentId, pop3Box.EMailAddress, FromEmail);

                    // Exclude a message sender
                    //output2Iternal.AddIgnoreRecipient(EMailMessage.GetSenderEmail(InMsg));

                    // Load InternalUser
                    foreach (int UserId in GetInternalUsersByIncidentId(IncidentId))
                    {
                        output2Iternal.AddRecipient(UserId);
                        retVal.Add(UserId);
                    }

                    // Load InformationRecipientList
                    //				foreach(int infoRecipient in IncidentBoxDocument.Load(incidentBox.IncidentBoxId).EMailRouterBlock.InformationRecipientList)
                    //				{
                    //					output2Iternal.AddRecipient(infoRecipient);
                    //				}

                    foreach (OutputMessage outputMsg in output2Iternal.Create())
                    {
                        //try
                        //{
                        SmtpClientUtility.SendMessage(OutgoingEmailServiceType.HelpDeskEmailBox, pop3Box.EMailRouterPop3BoxId, outputMsg.MailFrom, outputMsg.RcptTo, outputMsg.Subject, outputMsg.Data);
                        //}
                        //catch(Exception ex)
                        //{
                        //    System.Diagnostics.Trace.WriteLine(ex);
                        //    Log.WriteError(ex.ToString());
                        //}
                    }
                }

                // Internal -> Extrenal
                string publicEmail = FindEMailRouterPublicEmail(IncidentId);

                if (publicEmail!=string.Empty)
                {
                    //EMailRouterPop3Box externalPop3Box = EMailRouterPop3Box.Load(realEMailBoxId);

                    OutputMessageCreator output2External = new OutputMessageCreator(InMsg, IncidentId, publicEmail, publicEmail);

                    // Load External Senders
            //					foreach(string exRecipient in EMailMessage.GetExternalSendersByIncidentId(IncidentId))
            //					{
            //						output2External.AddRecipient(exRecipient);
            //					}

                    // Load External Senders
                    foreach (EMailIssueExternalRecipient exRecipient in EMailIssueExternalRecipient.List(IncidentId))
                    {
                        output2External.AddRecipient(exRecipient.EMail);
                    }

                    // 2007-03-12 RecipientEmails Addon
                    if (RecipientEmails != null)
                    {
                        foreach (string exItem in RecipientEmails)
                        {
                            int emailUserId = DBUser.GetUserByEmail(exItem, false);
                            if (emailUserId > 0)
                            {
                                if (!retVal.Contains(emailUserId))
                                {
                                    output2External.AddRecipient(exItem);
                                    retVal.Add(emailUserId);
                                }
                            }
                            else
                                output2External.AddRecipient(exItem);
                        }
                    }
                    //

                    int emailBoxId = EMail.EMailRouterOutputMessage.FindEMailRouterPublicId(IncidentId);

                    foreach(OutputMessage outputMsg in output2External.Create())
                    {
                        //try
                        //{
                        SmtpClientUtility.SendMessage(OutgoingEmailServiceType.HelpDeskEmailBox, emailBoxId, outputMsg.MailFrom, outputMsg.RcptTo, outputMsg.Subject, outputMsg.Data);
                        //}
                        //catch(Exception ex)
                        //{
                        //    System.Diagnostics.Trace.WriteLine(ex);
                        //    Log.WriteError(ex.ToString());
                        //}
                    }
                }
                #endregion
            }
            else
            {
                if (!settings.AllowEMailRouting)
                    return retVal;

                EMailRouterPop3Box internalPop3Box = EMailRouterPop3Box.ListInternal();
                if (internalPop3Box == null)
                    return retVal;

                #region // External -> Internal
                // External -> Internal

                string SenderName = EMailMessage.GetSenderName(InMsg);
                string FromEmail = SenderName==string.Empty?internalPop3Box.EMailAddress:
                    string.Format("\"{0}\" <{1}>",
                    SenderName,
                    internalPop3Box.EMailAddress);

                OutputMessageCreator output = new OutputMessageCreator(InMsg, IncidentId, internalPop3Box.EMailAddress, FromEmail);

                string Subject = (InMsg.Subject==null?string.Empty:InMsg.Subject);

                if(Subject==string.Empty)
                {
                    // OZ: Maybe:  Set Default Inicdent Title if subject is empty
                    //Subject = Incident.GetIncidentTitle(IncidentId);
                }

                if(TicketUidUtil.LoadFromString(Subject)==string.Empty)
                    output.Subject = string.Format("[{0}] {1}",TicketUidUtil.Create(incidentBox.IdentifierMask,IncidentId), Subject);

                foreach(int UserId in GetInternalUsersByIncidentId(IncidentId))
                {
                    output.AddRecipient(UserId);
                    retVal.Add(UserId);
                }

            //				IncidentBoxDocument incidentDoc = IncidentBoxDocument.Load(incidentBox.IncidentBoxId);
            //
            //				foreach(int infoRecipient in incidentDoc.EMailRouterBlock.InformationRecipientList)
            //				{
            //					output.AddRecipient(infoRecipient);
            //				}

                foreach(OutputMessage outputMsg in output.Create())
                {
                    //try
                    //{
                    SmtpClientUtility.SendMessage(OutgoingEmailServiceType.HelpDeskEmailBox, internalPop3Box.EMailRouterPop3BoxId, outputMsg.MailFrom, outputMsg.RcptTo, outputMsg.Subject, outputMsg.Data);
                    //}
                    //catch(Exception ex)
                    //{
                    //    System.Diagnostics.Trace.WriteLine(ex);
                    //    Log.WriteError(ex.ToString());
                    //}
                }
                #endregion
            }

            return retVal;
        }
Пример #4
0
 public static ArrayList Send(int IncidentId, EMailRouterPop3Box pop3Box, Pop3Message InMsg)
 {
     return Send(IncidentId, pop3Box, InMsg, null);
 }
Пример #5
0
        /// <summary>
        /// Creates the new incident.
        /// </summary>
        /// <param name="EMailMessageId">The E mail message id.</param>
        /// <param name="emailBox">The email box.</param>
        /// <param name="msg">The MSG.</param>
        /// <returns></returns>
        public static int CreateNewIncident(int EMailMessageId, EMailRouterPop3Box emailBox, Pop3Message msg)
        {
            IEMailIncidentMapping mappingHandler = EMailIncidentMappingHandler.LoadHandler(emailBox.Settings.SelectedHandlerId);

            // Step. Mapping
            IncidentInfo incidentInfo = mappingHandler.Create(emailBox, msg);

            // Set Creator
            UserLight prevUser = LogOnCreator(incidentInfo.CreatorId, msg);

            incidentInfo.CreatorId = Security.CurrentUser.UserID;

            // Step. Evaluate IncidentBox
            IncidentBox incidentBox = null;

            if (incidentInfo.IncidentBoxId != -1)
                incidentBox = IncidentBox.Load(incidentInfo.IncidentBoxId);
            else
                incidentBox = IncidentBoxRule.Evaluate(incidentInfo);

            // Step. Create Incident
            int IncidentId = Incident.CreateFromEmail(incidentInfo.Title,
                incidentInfo.Description,
                incidentInfo.ProjectId,
                incidentInfo.TypeId,
                incidentInfo.PriorityId,
                incidentInfo.SeverityId,
                incidentBox.Document.GeneralBlock.TaskTime,
                incidentBox.Document.GeneralBlock.ExpectedDuration,
                incidentBox.Document.GeneralBlock.ExpectedResponseTime,
                incidentBox.Document.GeneralBlock.ExpectedAssignTime,
                incidentInfo.GeneralCategories,
                incidentInfo.IncidentCategories,
                incidentBox.IncidentBoxId,
                EMailMessageId,
                incidentInfo.OrgUid,
                incidentInfo.ContactUid);

            return IncidentId;
        }
Пример #6
0
        /// <summary>
        /// Checks the specified email box.
        /// </summary>
        /// <param name="emailBox">The email box.</param>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        public static EMailMessageAntiSpamRuleRusult Check(EMailRouterPop3Box emailBox, Pop3Message message)
        {
            // 2007-01-09: Check Empty From and Sender
            if (message.Sender == null && message.From == null || message.To == null)
                return EMailMessageAntiSpamRuleRusult.Deny;

            EMailMessageAntiSpamRule[] antiSpamRules = EMailMessageAntiSpamRule.List();

            // Load Rules
            //EMailMessageAntiSpamRule[] antiSpamRules = _antiSpamRules;

            // Check Rules

            foreach (EMailMessageAntiSpamRule rule in antiSpamRules)
            {
                if (((EMailMessageAntiSpamRuleType)rule.RuleType) != EMailMessageAntiSpamRuleType.Service)
                {
                    string KeyValue = GetStringFromEmailByKey(message, rule.Key);

                    if (KeyValue != null)
                    {
                        switch ((EMailMessageAntiSpamRuleType)rule.RuleType)
                        {
                            case EMailMessageAntiSpamRuleType.Contains:
                                foreach (string ContainsSubStr in rule.Value.Split(';'))
                                {
                                    string TrimContainsSubStr = ContainsSubStr.Trim();
                                    if (TrimContainsSubStr != string.Empty)
                                    {
                                        if (TrimContainsSubStr.IndexOfAny(new char[] { '*', '?' }) != -1)
                                        {
                                            if (Pattern.Match(KeyValue, TrimContainsSubStr))
                                                return rule.Accept ? EMailMessageAntiSpamRuleRusult.Accept : EMailMessageAntiSpamRuleRusult.Deny;
                                        }
                                        else
                                        {
                                            if (KeyValue.IndexOf(TrimContainsSubStr) != -1)
                                                return rule.Accept ? EMailMessageAntiSpamRuleRusult.Accept : EMailMessageAntiSpamRuleRusult.Deny;
                                        }
                                    }
                                }
                                break;
                            case EMailMessageAntiSpamRuleType.IsEqual:
                                if (string.Compare(KeyValue, rule.Value, true) == 0)
                                    return rule.Accept ? EMailMessageAntiSpamRuleRusult.Accept : EMailMessageAntiSpamRuleRusult.Deny;
                                break;
                            case EMailMessageAntiSpamRuleType.RegexMatch:
                                Match match = Regex.Match(KeyValue, rule.Value);
                                if ((match.Success && (match.Index == 0)) && (match.Length == KeyValue.Length))
                                    return rule.Accept ? EMailMessageAntiSpamRuleRusult.Accept : EMailMessageAntiSpamRuleRusult.Deny;
                                break;
                        }
                    }
                }
                else
                {
                    string FromEmail = EMailMessage.GetSenderEmail(message);

                    switch (rule.Key)
                    {
                        case BlackListServiceName:
                            if (BlackListItem.Contains(FromEmail))
                                return rule.Accept ? EMailMessageAntiSpamRuleRusult.Accept : EMailMessageAntiSpamRuleRusult.Deny;
                            break;
                        case WhiteListServiceName:
                            if (WhiteListItem.Contains(FromEmail))
                                return rule.Accept ? EMailMessageAntiSpamRuleRusult.Accept : EMailMessageAntiSpamRuleRusult.Deny;
                            break;
                        case TicketServiceName:
                            if (message.Subject != null && TicketUidUtil.LoadFromString(message.Subject) != string.Empty)
                                return rule.Accept ? EMailMessageAntiSpamRuleRusult.Accept : EMailMessageAntiSpamRuleRusult.Deny;
                            break;
                        case IncidentBoxRulesServiceName:
                            // Step 1. Get Incident Info
                            IEMailIncidentMapping mappingHandler = EMailIncidentMappingHandler.LoadHandler(emailBox.Settings.SelectedHandlerId);
                            IncidentInfo incidentInfo = mappingHandler.Create(emailBox, message);

                            // Step 2. Evaluate IncidentBoxRules
                            IncidentBox box = IncidentBoxRule.Evaluate(incidentInfo, false);
                            if (box != null)
                                return rule.Accept ? EMailMessageAntiSpamRuleRusult.Accept : EMailMessageAntiSpamRuleRusult.Deny;
                            break;
                    }

                }
            }

            return EMailMessageAntiSpamRuleRusult.Pending;
        }
Пример #7
0
        protected override ResourceInfo GetResourceInfo(WebDavTicket ticket)
        {
            ResourceInfo retVal = new ResourceInfo();
            EmailStorageAbsolutePath absPath = ticket.AbsolutePath as EmailStorageAbsolutePath;
            if(absPath == null)
                throw new ArgumentException("absPath");

            EMailMessageRow row = new EMailMessageRow(absPath.EmailMsgId);
            MemoryStream memStream = new MemoryStream(row.EmlMessage.Length);
            memStream.Write(row.EmlMessage, 0, row.EmlMessage.Length);
            memStream.Position = 0;

            Pop3Message message = new Pop3Message(memStream);
            int attachmentIndex = absPath.EmailAttachmentIndex;
            Mediachase.IBN.Business.EMail.EMailMessageInfo.AttachmentData entry =
                            EMailMessageInfo.GetAttachment(message.MimeEntries, ref attachmentIndex);

            if (entry != null)
            {

                retVal.AbsolutePath = ticket.ToString();
                retVal.Tag = entry;
                retVal.Name = entry.FileName;
                //Fix ET:26-11-2008 Solve trouble inconsistency Content-Type email attachment and file extension
                //try first get Content-Type by file extension
                retVal.ContentType = ContentTypeResolver.Resolve(Path.GetExtension(entry.FileName));
                if (String.IsNullOrEmpty(retVal.ContentType))
                {
                    //otherwise set ContentType as ContentType email attachment
                    retVal.ContentType = entry.ContentType;
                }
                retVal.ContentLength = entry.Data.Length;
                retVal.ParentName = "root";
                DateTime created = Database.DBCommon.GetLocalDate(Security.CurrentUser.TimeZoneId, row.Created);
                retVal.Created = created;
                retVal.Modified = created;
            }

            return retVal;
        }
Пример #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NewPop3MessageEventArgs"/> class.
 /// </summary>
 /// <param name="Message">The message.</param>
 public NewPop3MessageEventArgs(Pop3Message Message)
 {
     _message = Message;
 }
Пример #9
0
 private int RegisterEmail(int EMailRouterPop3BoxId, Pop3Message msg)
 {
     return EMailMessage.Create(EMailRouterPop3BoxId, msg);
 }
Пример #10
0
        public MHTHelper(Pop3Message message)
        {
            _OwnerMessage = message;

            CheckHTMLText(this.OwnerMessage.MimeEntries);
        }
Пример #11
0
        //        public static string[] GetExternalSendersByIncidentId(int IncidentId)
        //        {
        //            return EMailMessageRow.GetExternalSendersByIncidentId(IncidentId);
        //        }
        /// <summary>
        /// Logs the on creator.
        /// </summary>
        /// <param name="DefaultCreatorId">The default creator id.</param>
        /// <param name="msg">The MSG.</param>
        /// <returns></returns>
        internal static UserLight LogOnCreator(int DefaultCreatorId, Pop3Message msg)
        {
            if (Security.CurrentUser != null)
                return Security.CurrentUser;

            int creatorId = DefaultCreatorId;

            int emailUser = DBUser.GetUserByEmail(EMailMessage.GetSenderEmail(msg), false);

            if (emailUser > 0)
            {
                // OZ: 2007-01-26: Fix problem: Mediachase.IBN.Business.AccessDeniedException: Access denied.
                //   at Mediachase.IBN.Business.Incident.CreateFromEmail
                using (IDataReader reader = DBUser.GetUserInfo(emailUser))
                {
                    if (reader.Read())
                    {
                        if (!(bool)reader["IsActive"])
                        {
                            emailUser = -1;
                        }
                    }
                    else
                    {
                        emailUser = -1;
                    }
                }
                //
            }

            if (emailUser > 0)
                creatorId = emailUser;

            UserLight creator = UserLight.Load(creatorId);
            return Security.SetCurrentUser(creator);
        }
Пример #12
0
        /// <summary>
        /// Gets the name of the sender.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        internal static string GetSenderName(Pop3Message message)
        {
            if (message.Headers["Reply-To"] != null)
                return EMailMessage.ExtractFirstEmail(message.Headers["Reply-To"]);

            //if (message.Headers["Sender"] != null)
            //    return EMailMessage.ExtractFirstShowName(message.Headers["Sender"]);

            return EMailMessage.ExtractFirstShowName(message.Headers["From"]);
        }
Пример #13
0
        /// <summary>
        /// Gets the POP3 message bytes.
        /// </summary>
        /// <param name="msg">The MSG.</param>
        /// <returns></returns>
        internal static byte[] GetPop3MessageBytes(Pop3Message msg)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                byte[] tmpBuffer = new byte[64 * 1024];

                msg.InputStream.Position = 0;

                int RealRead = 0;
                while ((RealRead = msg.InputStream.Read(tmpBuffer, 0, 64 * 1024)) != 0)
                {
                    ms.Write(tmpBuffer, 0, RealRead);
                }
                ms.Flush();
                ms.Capacity = (int)ms.Length;
                return ms.GetBuffer();
            }
        }
Пример #14
0
        /// <summary>
        /// Processes the X ibn headers.
        /// </summary>
        /// <param name="IncidentId">The incident id.</param>
        /// <param name="ThreadNodeId">The thread node id.</param>
        /// <param name="Msg">The MSG.</param>
        /// <returns></returns>
        public static bool ProcessXIbnHeaders(int IncidentId, int ThreadNodeId, Pop3Message Msg)
        {
            bool bRetVal = true;

            ForumStorage.NodeType nodeType = ForumStorage.NodeType.Internal;

            ForumThreadNodeSettingCollection settings = new ForumThreadNodeSettingCollection(ThreadNodeId);

            if (settings.Contains(ForumThreadNodeSetting.Incoming))
                nodeType = ForumStorage.NodeType.Incoming;
            else if (settings.Contains(ForumThreadNodeSetting.Outgoing))
                nodeType = ForumStorage.NodeType.Outgoing;

            bool bSetIncidentState = false;
            ObjectStates cmdObjectStates = ObjectStates.Active;
            int newResponsibleId = 0;

            foreach (string HeaderName in Msg.Headers.AllKeys)
            {
                string UpHeaderName = HeaderName.ToUpper();

                if (UpHeaderName.StartsWith("X-IBN-"))
                {
                    switch (UpHeaderName)
                    {
                        case "X-IBN-STATE":
                            if (Msg.Headers[HeaderName].Trim() != "0")
                            {
                                cmdObjectStates = (ObjectStates)Enum.Parse(typeof(ObjectStates), Msg.Headers[HeaderName]);

                                if (cmdObjectStates >= ObjectStates.Upcoming &&
                                     cmdObjectStates <= ObjectStates.OnCheck)
                                {
                                    bSetIncidentState = true;
                                }
                                else
                                {
                                    // OZ: Wrong Object State
                                    cmdObjectStates = ObjectStates.Active;
                                }
                            }
                            break;
                        case "X-IBN-PRIVATEMSG":
                            if (Msg.Headers[HeaderName].Trim() != "0")
                            {
                                XIbnHeaderCommand.SetPrivateStatus(ThreadNodeId);
                                nodeType = ForumStorage.NodeType.Internal;
                                bRetVal = false;
                            }
                            break;
                        case "X-IBN-RESOLUTION":
                            if (Msg.Headers[HeaderName].Trim() != "0")
                            {
                                XIbnHeaderCommand.SetResolutionStatus(ThreadNodeId);
                            }
                            break;
                        case "X-IBN-WORKAROUND":
                            if (Msg.Headers[HeaderName].Trim() != "0")
                            {
                                XIbnHeaderCommand.SetWorkaroundStatus(ThreadNodeId);
                            }
                            break;
                        case "X-IBN-RESPONSIBLE":
                            if (Msg.Headers[HeaderName].Trim() != "0")
                            {
                                newResponsibleId = int.Parse(Msg.Headers[HeaderName]);
                            }
                            break;
                        default:
                            XIbnHeaderCommand.Unknown(IncidentId, Msg.Headers[HeaderName]);
                            break;
                    }
                }
            }

            // Set Default IBN Object State
            if (!bSetIncidentState)
            {
                if (nodeType == ForumStorage.NodeType.Incoming)
                {
                    IncidentBoxDocument document = IncidentBoxDocument.Load(Incident.GetIncidentBox(IncidentId));

                    switch (document.EMailRouterBlock.IncomingEMailAction)
                    {
                        case ExternalEMailActionType.None:
                            break;
                        case ExternalEMailActionType.SetReOpenState:
                            XIbnHeaderCommand.SetIncidentState(nodeType, document, IncidentId, ThreadNodeId, ObjectStates.ReOpen);
                            break;
                    }
                }
                else if (nodeType == ForumStorage.NodeType.Outgoing)
                {
                    IncidentBoxDocument document = IncidentBoxDocument.Load(Incident.GetIncidentBox(IncidentId));

                    switch (document.EMailRouterBlock.OutgoingEMailAction)
                    {
                        case InternalEMailActionType.None:
                            break;
                        case InternalEMailActionType.SendToCheck:
                            XIbnHeaderCommand.SetIncidentState(nodeType, document, IncidentId, ThreadNodeId, ObjectStates.OnCheck);
                            break;
                        case InternalEMailActionType.SetCompletedState:
                            XIbnHeaderCommand.SetIncidentState(nodeType, document, IncidentId, ThreadNodeId, ObjectStates.Completed);
                            break;
                        case InternalEMailActionType.SetSuspendState:
                            XIbnHeaderCommand.SetIncidentState(nodeType, document, IncidentId, ThreadNodeId, ObjectStates.Suspended);
                            break;
                    }
                }
            }
            else
            {
                IncidentBoxDocument document = IncidentBoxDocument.Load(Incident.GetIncidentBox(IncidentId));
                XIbnHeaderCommand.SetIncidentState(nodeType, document, IncidentId, ThreadNodeId, cmdObjectStates);
            }

            // OZ: 2008-11-24 ChangeResponsible, -1 = NotSet, -2 = Group
            if (newResponsibleId != 0)
            {
                XIbnHeaderCommand.ChangeResponsible(IncidentId, newResponsibleId);
            }

            return bRetVal;
        }
Пример #15
0
        /// <summary>
        /// Sends the auto reply.
        /// </summary>
        /// <param name="IncidentId">The incident id.</param>
        /// <param name="From">From.</param>
        /// <param name="To">To.</param>
        internal static void SendAutoReply(int IncidentId, string From, string To)
        {
            IncidentBox incidentBox = IncidentBox.Load( Incident.GetIncidentBox(IncidentId));

            if(!incidentBox.Document.EMailRouterBlock.SendAutoReply)
                return;

            Alerts2.Message msg = Alerts2.GetMessage(incidentBox.Document.GeneralBlock.AutoReplyEMailSubjectTemplate,
                incidentBox.Document.GeneralBlock.AutoReplyEMailBodyTemplate,
                SystemEventTypes.Issue_Created,
                IncidentId, null,
                -1,
                Security.CurrentUser.UserID);

            string subject = msg.Subject, body = msg.Body;

            MemoryStream emlMessage = new MemoryStream();
            byte[] tmpBuffer = null;

            #region Fill Pop3 Message Stream
            // Create Pop3 Message Headers
            StringBuilder sbHeaders = new StringBuilder();

            sbHeaders.AppendFormat("Date: {0}", GetEMailCreationDate()).Append("\r\n");
            sbHeaders.Append("From: [email protected]").Append("\r\n");
            sbHeaders.Append("To: [email protected]").Append("\r\n");
            sbHeaders.AppendFormat("Subject: {0}", Rfc822HeaderCollection.Encode2AsciiString(subject)).Append("\r\n");
            sbHeaders.Append("MIME-Version: 1.0").Append("\r\n");
            sbHeaders.Append("Content-Type: multipart/mixed; boundary=\"----------7E143249668A83E\"").Append("\r\n");
            sbHeaders.Append("\r\n");

            tmpBuffer = Encoding.ASCII.GetBytes(sbHeaders.ToString());
            emlMessage.Write(tmpBuffer,0, tmpBuffer.Length);

            // Create Pop3 Message Entry
            StringBuilder sbMessage = new StringBuilder();

            sbMessage.Append("------------7E143249668A83E").Append("\r\n");

            // IF MESSAGE IS PLAIN TEXT
            //sbMessage.Append("Content-Type: text/plain; charset=utf-8").Append("\r\n");

            // IF MESSAGE IS HTML TEXT
            sbMessage.Append("Content-Type: text/html; charset=utf-8").Append("\r\n");

            sbMessage.Append("Content-Transfer-Encoding: base64").Append("\r\n");
            sbMessage.Append("\r\n");

            // OZ Fixed 500 5.3.3 Line too long (in reply to end of DATA command)
            sbMessage.Append(Convert.ToBase64String(Encoding.UTF8.GetBytes(body), Base64FormattingOptions.InsertLineBreaks)).Append("\r\n");

            tmpBuffer = Encoding.ASCII.GetBytes(sbMessage.ToString());
            emlMessage.Write(tmpBuffer,0, tmpBuffer.Length);

            // Add Final Line
            tmpBuffer = Encoding.ASCII.GetBytes("------------7E143249668A83E--\r\n\r\n");
            emlMessage.Write(tmpBuffer,0, tmpBuffer.Length);

            #endregion

            Pop3Message InMsg = new Pop3Message(emlMessage);

            OutputMessageCreator outputAutoReply = new OutputMessageCreator(InMsg, IncidentId, From, From);
            outputAutoReply.AddRecipient(To);

            int emailBoxId = EMail.EMailRouterOutputMessage.FindEMailRouterPublicId(IncidentId);

            foreach(OutputMessage outputMsg in outputAutoReply.Create())
            {
                try
                {
                    SmtpClientUtility.SendMessage(OutgoingEmailServiceType.HelpDeskEmailBox, emailBoxId, outputMsg.MailFrom, outputMsg.RcptTo, outputMsg.Subject, outputMsg.Data);
                }
                catch(Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine(ex);
                    Log.WriteError(ex.ToString());
                }
            }
        }
Пример #16
0
        protected void AddAttachments(FileStorage storage, int FolderId, Pop3Message message, int userId)
        {
            ArrayList Attachments = new ArrayList();

            ExtractAttachments(Attachments, message.MimeEntries);
            UploadAttachments(storage, FolderId, Attachments, userId);
        }
Пример #17
0
        protected string ParseFolderPattern(string FolderPattern, Pop3Message message, int userId)
        {
            Regex contentParser = new Regex(@"(?<AT>\x5B(?<ATName>(\w|\.|_)+)(\x28(?<ATParam>[^\x29]*)\x29)?\x5D)");
            MatchCollection matchList = contentParser.Matches(FolderPattern);
            foreach(Match matchItem in matchList)
            {
                string strAT = matchItem.Groups["AT"].Value;
                string strATName = matchItem.Groups["ATName"].Value;
                string strATParam = matchItem.Groups["ATParam"].Value;
                string str = String.Empty;

                MailAddress from = message.Sender;
                if(from == null)
                    from = message.From;

                switch(strATName)
                {
                    case "UserName":
                        if (userId != -1)
                        {
                            str = User.GetUserName(userId);
                        }
                        else str = message.Sender.Address;
                        break;
                    case "From":
                        str = from.Address;
                        break;
                    case "Subject":
                        str = message.Subject;
                        break;
                    case "Date.Now":
                        str = DateTime.Now.ToString(strATParam);
                        break;
                    case "Date.UtcNow":
                        str = DateTime.UtcNow.ToString(strATParam);
                        break;
                    case "Date":
                        str = message.Date.ToString(strATParam);
                        break;
                    case "Importance":
                        str = message.Importance;
                        break;
                    case "MessageID":
                        str = message.MessageID;
                        break;
                    case "Sender":
                        str = message.Sender==null?"SenderIsNull":message.Sender.Address;
                        break;
                    case "To":
                        str = message.To;
                        break;
                    case "Header":
                        str = message.Headers[strATParam];
                        break;
                    default:
                        str = strAT;
                        break;
                }
                FolderPattern = FolderPattern.Replace(strAT, str);
            }
            return FolderPattern.Trim();
        }
Пример #18
0
        protected override void OnProcessPop3Message(Pop3Box box, Mediachase.Net.Mail.Pop3Message message)
        {
            try
            {
                // Step 0. Get settings
                FileSettings settings = GetSettings(box);

                // Step 0.5 Create storage
                string containerKey = "Workspace";
                if (settings.ContainerKey != String.Empty)
                {
                    containerKey = settings.ContainerKey;
                }
                BaseIbnContainer baseContainer = BaseIbnContainer.Create("FileLibrary", containerKey);
                FileStorage      storage       = (FileStorage)baseContainer.LoadControl("FileStorage");

                // Step 1. Get Email sender info
                MailAddress from = message.Sender;
                if (from == null)
                {
                    from = message.From;
                }

                // Step 2. Get Ibn User
                int userId = GetUserIdByEmail(from.Address, settings.OnlyExternalSenders);

                if (userId != -1)
                {
                }
                else
                {
                    if (settings.AutoKillForUnknown)
                    {
                        return;
                    }
                }

                // Step 3. Find Folder
                int FolderId = settings.FolderId;
                if (settings.FolderPattern != String.Empty)
                {
                    String FolderName = ValidatePatternPath(ParseFolderPattern(settings.FolderPattern, message, userId));

                    Mediachase.IBN.Business.ControlSystem.DirectoryInfo dirInfo = storage.GetDirectory(FolderId, FolderName, true);
                    if (dirInfo != null)
                    {
                        FolderId = dirInfo.Id;
                    }
                    else
                    {
                        FolderId = -1;
                    }
                }

                // Step 3. Create Files
                AddAttachments(storage, FolderId, message, userId);

                // Step 4. Create EML File
                if (settings.SaveMessageBodyAsEml)
                {
                    UploadEmlFile(storage, FolderId, userId, message);
                }
                // Step 5. Create MHT File
                if (settings.SaveMessageBodyAsMht)
                {
                    UploadMhtFile(storage, FolderId, userId, message);
                }
                // Step 5. Create MSG File
                if (settings.SaveMessageBodyAsMsg)
                {
                    UploadMsgFile(storage, FolderId, userId, message);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex);
                throw;
            }
        }
Пример #19
0
        protected void UploadEmlFile(FileStorage storage, int FolderId, int UserId, Pop3Message message)
        {
            message.InputStream.Position = 0;

            string FileName = "Original_Message.eml";

            int index = 0;
            while (storage.FileExist(FileName, FolderId))
            {
                FileName = String.Format("Original_Message{0}.eml", index++);
            }

            storage.SaveFile(FolderId, FileName, string.Empty, UserId, DateTime.Now, message.InputStream);
        }
Пример #20
0
 /// <summary>
 /// Raises the error event.
 /// </summary>
 /// <param name="args">The <see cref="T:Mediachase.EMailRouter.ExceptionAbortEventArgs"/> instance containing the event data.</param>
 private void RaiseNewMessageEvent(Pop3Message message)
 {
     OnNewMessageEvent(new NewPop3MessageEventArgs(message));
 }
Пример #21
0
        protected void UploadMhtFile(FileStorage storage, int FolderId, int UserId, Pop3Message message)
        {
            MHTHelper helper = new MHTHelper(message);

            using(MemoryStream memStream = new MemoryStream())
            {
                using (StreamWriter writer = new StreamWriter(memStream))
                {
                    helper.CreateMHT(writer);

                    writer.Flush();

                    memStream.Seek(0,SeekOrigin.Begin);

                    string FileName = "Original_Message.mht";
                    int index = 0;
                    while (storage.FileExist(FileName, FolderId)) {
                        FileName = String.Format("Original_Message{0}.mht", index++);
                    }

                    storage.SaveFile(FolderId, FileName, string.Empty, UserId, DateTime.Now, memStream);
                }
            }
        }
Пример #22
0
        /// <summary>
        /// Checks the specified file name.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        public static EMailMessageAntiSpamRuleRusult Check(string fileName)
        {
            System.IO.StreamReader st = new System.IO.StreamReader(fileName, System.Text.Encoding.Default);
            string strmsg = st.ReadToEnd();

            byte[] buffer = System.Text.Encoding.Default.GetBytes(strmsg);
            System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer, 0, buffer.Length, true, true);

            Pop3Message msg = new Pop3Message(ms);

            return Check(EMailRouterPop3Box.ListExternal()[0], msg);
        }
Пример #23
0
        protected void UploadMsgFile(FileStorage storage, int FolderId, int UserId, Pop3Message message)
        {
            System.Reflection.Assembly asm = typeof(FileExtendedPop3MessageHandler).Assembly;
            using (Stream stream = asm.GetManifestResourceStream("Mediachase.IBN.Business.Resources.template.msg"))
            {
                using(MemoryStream memStream = new MemoryStream())
                {
                    using (MsgHelper helper = new MsgHelper(stream))
                    {
                        //helper.SetHtmlBody(message.From.Email);
                        helper.SetSubject(message.Subject);
                        helper.SetBody(message.BodyText);
                        if (message.BodyHtml==null || message.BodyHtml.Trim()==String.Empty)
                        {
                            helper.SetHtmlBody(message.BodyText);
                        }
                        else helper.SetHtmlBody(message.BodyHtml);

                        MailAddress from = message.Sender;
                        if (from == null)
                            from = message.From;

                        helper.SetSenderEmail(from.Address);
                        helper.SetSenderName(from.DisplayName);
                        helper.SetReceiverName(message.To);
                        helper.SetDisplayTo(message.To);
                        helper.SetCreationTimes(DateTime.UtcNow);

                        helper.Commit();

                        helper.createMSG(memStream);
                        memStream.Flush();
                        memStream.Seek(0,SeekOrigin.Begin);

                        string FileName = "Original_Message.msg";
                        int index = 0;
                        while (storage.FileExist(FileName, FolderId))
                        {
                            FileName = String.Format("Original_Message{0}.msg", index++);
                        }
                        storage.SaveFile(FolderId, FileName, string.Empty, UserId, DateTime.Now, memStream);
                    }
                }
            }
        }
Пример #24
0
 private static string GetStringFromEmailByKey(Pop3Message message, string Key)
 {
     switch (Key)
     {
         case "From":
             return message.Headers["From"];
         case "Sender":
             return message.Headers["Sender"];
         case "Reply-To":
             return message.Headers["Reply-To"];
         case "To":
             return message.Headers["To"];
         case "Subject":
             return message.Subject;
         case "Body":
             return message.BodyText;
         case "SubjectOrBody":
             return message.Subject + "\r\n" + message.BodyText;
         default:
             return message.Headers[Key];
     }
 }
Пример #25
0
        /// <summary>
        /// Creates the specified message.
        /// </summary>
        /// <param name="EMailRouterPop3BoxId">The E mail router POP3 box id.</param>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        public static int Create(int EMailRouterPop3BoxId, Pop3Message message)
        {
            if (message == null)
                throw new ArgumentNullException("message");

            EMailMessageRow newRow = new EMailMessageRow();

            newRow.EMailRouterPop3BoxId = EMailRouterPop3BoxId;
            //newRow.Created = DateTime.UtcNow;
            newRow.From = EMailMessage.GetSenderEmail(message);

            //if (message.Sender != null)
            //    newRow.From = EMailMessage.ExtractFirstEmail(message.Sender.Email);
            //else
            //    newRow.From = EMailMessage.ExtractFirstEmail(message.From.Email);

            newRow.To = EMailMessage.ExtractFirstEmail(message.To);

            newRow.Subject = message.Subject == null ? string.Empty : message.Subject;

            newRow.EmlMessage = GetPop3MessageBytes(message);

            newRow.Update();

            return newRow.PrimaryKeyId;
        }