Exemplo n.º 1
0
        public static void OpenEml(int IncidentId, int EMailMessageId, Stream outputStream)
        {
            Pop3Message message     = EMailMessage.GetPop3Message(EMailMessageId);
            IncidentBox incidentBox = IncidentBox.Load(Incident.GetIncidentBox(IncidentId));

            EMailRouterPop3Box emailBox = EMailRouterPop3Box.ListInternal();

            string SenderName = EMailMessage.GetSenderName(message);

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

            OutputMessageCreator output = new OutputMessageCreator(message, IncidentId, emailBox.EMailAddress, FromEmail);

            output.AddRecipient(Security.CurrentUser.UserID);

            string Subject = (message.Subject == null?string.Empty:message.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);
            }


            OutputMessage outputMsg = (OutputMessage)output.Create()[0];

            outputStream.Write(outputMsg.Data, 0, outputMsg.Data.Length);

            outputStream.Flush();
        }
Exemplo n.º 2
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);
        }
Exemplo n.º 3
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());
                }
            }
        }
Exemplo n.º 4
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());
                }
            }
        }
Exemplo n.º 5
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;
        }
Exemplo n.º 6
0
        public static void OpenEml(int IncidentId, int EMailMessageId, Stream outputStream)
        {
            Pop3Message message = EMailMessage.GetPop3Message(EMailMessageId);
            IncidentBox incidentBox = IncidentBox.Load(Incident.GetIncidentBox(IncidentId));

            EMailRouterPop3Box emailBox = EMailRouterPop3Box.ListInternal();

            string SenderName = EMailMessage.GetSenderName(message);

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

            OutputMessageCreator output = new OutputMessageCreator(message, IncidentId, emailBox.EMailAddress, FromEmail);
            output.AddRecipient(Security.CurrentUser.UserID);

            string Subject = (message.Subject==null?string.Empty:message.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);

            OutputMessage outputMsg = (OutputMessage)output.Create()[0];
            outputStream.Write(outputMsg.Data, 0, outputMsg.Data.Length);

            outputStream.Flush();
        }
Exemplo n.º 7
0
        public static void SendMessage(string[] To, string Subject, string Body, Mediachase.IBN.Business.ControlSystem.DirectoryInfo Attachments, string Mode, NameValueCollection Params)
        {
            // Cleanup Temporary files
            DbEMailTempFile.CleanUp();

            #region Validate Arguments
            if (To == null)
                throw new ArgumentNullException("To");

            if (Subject == null)
                throw new ArgumentNullException("Subject");

            if (Body == null)
                throw new ArgumentNullException("Body");

            //if (To.Length == 0)
            //    throw new ArgumentOutOfRangeException("To", "Email recipient list is empty.");

            if (Mode == null)
                Mode = string.Empty;

            if (Params == null)
                Params = new NameValueCollection();
            #endregion

            string FromEmail = string.Empty;

            switch (Mode)
            {
                case EMailClient.IssueMode:
                case EMailClient.SmtpTestMode:
                    FromEmail = Alerts2.AlertSenderEmail;
                    break;
                default:
                    FromEmail = Security.CurrentUser.Email;
                    break;
            }

            string FullFromEmail = string.Format("\"{0} {1}\" <{2}>",
                Security.CurrentUser.LastName,
                Security.CurrentUser.FirstName,
                FromEmail);

            using (DbTransaction tran = DbTransaction.Begin())
            {
                EMailMessageLogSetting EmailLogSettings = EMailMessageLogSetting.Current;
                if (EmailLogSettings.IsActive)
                    EMailMessageLog.CleanUp(EmailLogSettings.Period);
                else
                    EmailLogSettings = null;

                Mode = Mode.ToLower();

                #region Pre-format incoming arguments
                switch (Mode)
                {
                    case EMailClient.IssueMode:
                        if (Params["IssueId"] == null)
                            throw new ArgumentNullException("Params[\"IssueId\"]");

                        int IssueId = int.Parse(Params["IssueId"]);

                        // TODO: Validate Subject & Ticket
                        if (TicketUidUtil.LoadFromString(Subject) == string.Empty)
                        {
                            IncidentBox incidentBox = IncidentBox.Load(Incident.GetIncidentBox(IssueId));

                            string IncidentTicket = Incident.GetIdentifier(IssueId);

                            if (incidentBox.Document.GeneralBlock.AllowOutgoingEmailFormat)
                            {
                                StringBuilder sb = new StringBuilder(incidentBox.Document.GeneralBlock.OutgoingEmailFormatSubject, 4096);

                                sb.Replace("[=Title=]", Subject);
                                sb.Replace("[=Ticket=]", IncidentTicket);
                                //sb.Replace("[=Text=]", Body);
                                sb.Replace("[=FirstName=]", Security.CurrentUser.FirstName);
                                sb.Replace("[=LastName=]", Security.CurrentUser.LastName);

                                Subject = sb.ToString();
                            }
                            else
                            {
                                Subject = string.Format("RE: [{0}] {1}",
                                    IncidentTicket,
                                    Subject);
                            }

                        }
                        break;
                    default:
                        break;
                }

                #endregion

                Pop3Message msg = Create(FullFromEmail, To, Subject, Body, Attachments);

                switch (Mode)
                {
                    case EMailClient.IssueMode:
                        #region Issue
                        int IssueId = int.Parse(Params["IssueId"]);

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

                        bool AllowEMailRouting = true;

                        EMailRouterIncidentBoxBlock settings = IncidentBoxDocument.Load(incidentBox.IncidentBoxId).EMailRouterBlock;
                        if (!settings.AllowEMailRouting)
                            AllowEMailRouting = false;

                        EMailRouterPop3Box internalPop3Box = EMailRouterPop3Box.ListInternal();
                        if (internalPop3Box == null)
                            AllowEMailRouting = false;

                        // Register Email Message
                        // OZ: [2007--05-25] Fix Problem Object reference not set to an instance of an object If (internalPop3Box == NULL)
                        int EMailMessageId = EMailMessage.Create(internalPop3Box!=null?
                            internalPop3Box.EMailRouterPop3BoxId : EMailRouterOutputMessage.FindEMailRouterPublicId(IssueId),
                            msg);

                        // Register Forume Node
                        int ThreadNodeId = EMailMessage.AddToIncidentMessage(true, IssueId, EMailMessageId, msg);

                        // Send Message

                        if (AllowEMailRouting)
                        {
                            ArrayList excludedUsers = EMailRouterOutputMessage.Send(IssueId, internalPop3Box, msg, To);
                            SystemEvents.AddSystemEvents(SystemEventTypes.Issue_Updated_Forum_MessageAdded, IssueId, -1, excludedUsers);
                        }
                        else
                        {
                            FromEmail = EMailRouterOutputMessage.FindEMailRouterPublicEmail(IssueId);
                            FullFromEmail = string.Format("\"{0} {1}\" <{2}>",
                                Security.CurrentUser.LastName,
                                Security.CurrentUser.FirstName,
                                FromEmail);

                            // Create OutputMessageCreator
                            OutputMessageCreator issueOutput = new OutputMessageCreator(msg,
                                -1,
                                FromEmail,
                                FullFromEmail);

                            // Fill Recipent
                            foreach (string ToItem in To)
                            {
                                issueOutput.AddRecipient(ToItem);
                            }

                            foreach (EMailIssueExternalRecipient exRecipient in EMailIssueExternalRecipient.List(IssueId))
                            {
                                issueOutput.AddRecipient(exRecipient.EMail);
                            }

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

                            //Send Smtp Message
                            foreach (OutputMessage outputMsg in issueOutput.Create())
                            {
                                SmtpClientUtility.SendMessage(OutgoingEmailServiceType.HelpDeskEmailBox, emailBoxId, outputMsg.MailFrom, outputMsg.RcptTo, outputMsg.Subject, outputMsg.Data);
                            }

                            ArrayList excludedUsers = new ArrayList();

                            foreach (string ToItem in To)
                            {
                                int emailUserId = DBUser.GetUserByEmail(ToItem, false);
                                if (emailUserId > 0)
                                    excludedUsers.Add(emailUserId);
                            }

                            SystemEvents.AddSystemEvents(SystemEventTypes.Issue_Updated_Forum_MessageAdded, IssueId, -1, excludedUsers);
                        }
                        #endregion
                        break;
                    case EMailClient.SmtpTestMode:
                        throw new NotImplementedException();
                        //OutputMessageCreator smtpTestOutput = new OutputMessageCreator(msg,
                        //    -1,
                        //    FromEmail,
                        //    FullFromEmail);

                        //// Fill Recipent
                        //foreach (string ToItem in To)
                        //{
                        //    smtpTestOutput.AddRecipient(ToItem);
                        //}

                        ////Send Smtp Message
                        //foreach (OutputMessage outputMsg in smtpTestOutput.Create())
                        //{
                        //    //SmtpClientUtility.DirectSendMessage(outputMsg.MailFrom, outputMsg.RcptTo, outputMsg.Subject, outputMsg.Data);
                        //    //SmtpBox.SendTestEmail(
                        //}
                        //break;
                    default:
                        #region Default
                        // Create OutputMessageCreator
                        OutputMessageCreator defaultOutput = new OutputMessageCreator(msg,
                            -1,
                            FromEmail,
                            FullFromEmail);

                        // Fill Recipent
                        foreach (string ToItem in To)
                        {
                            defaultOutput.AddRecipient(ToItem);
                        }

                        //Send Smtp Message
                        foreach (OutputMessage outputMsg in defaultOutput.Create())
                        {
                            SmtpClientUtility.SendMessage(OutgoingEmailServiceType.SendFile, null, outputMsg.MailFrom, outputMsg.RcptTo, outputMsg.Subject, outputMsg.Data);
                        }

                        #endregion
                        break;
                }

                if(Attachments!=null)
                    FileStorage.InnerDeleteFolder(Attachments.Id);

                tran.Commit();
            }
        }