コード例 #1
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();
            }
        }
コード例 #2
0
        private void BindDefaultValues()
        {
            string fromEmail = Security.CurrentUser.Email;

            if (IncidentId > 0)
            {
                fromEmail = EMailRouterOutputMessage.FindEMailRouterPublicEmail(IncidentId);
            }
            txtFrom.Text = String.Format(CultureInfo.InvariantCulture,
                                         "{1}&nbsp;&lt;{0}&gt;", fromEmail, Security.CurrentUser.DisplayName);
            lblCCTitle.Text = "";
            lblToTitle.Text = LocRM.GetString("tTo") + ":";
            if (IncidentId > 0)
            {
                NameValueCollection _params = new NameValueCollection();
                _params["IssueId"] = IncidentId.ToString();
                string[] erList = EMailClient.GetDefaultRecipientList(EMailClient.IssueMode, _params);
                for (int i = 0; i < erList.Length; i++)
                {
                    string sName = GetNameByEMail(erList[i]);
                    if (sName != "")
                    {
                        lblCC.Text += String.Format(CultureInfo.InvariantCulture, "{0} &lt;{1}&gt;; ", sName, erList[i]);
                    }
                    else
                    {
                        lblCC.Text += erList[i] + "; ";
                    }
                }

                string sValue = EMailMessage.GetOutgoingEmailFormatBodyPreview(IncidentId).Replace("[=Text=]", "");
                if (NodeId > 0)
                {
                    EMailMessageInfo mi = EMailMessageInfo.Load(NodeId);
                    sValue += "<br/>" + "<blockquote style='border-left: 2px solid rgb(0, 0, 0); padding-right: 0px; padding-left: 5px; margin-left: 5px; margin-right: 0px;' dir='ltr'>" + mi.HtmlBody + "</blockquote>";
                }
                fckEditor.Text = sValue;

                using (IDataReader reader = Incident.GetIncident(IncidentId))
                {
                    if (reader.Read())
                    {
                        txtSubject.Text = string.Format(CultureInfo.InvariantCulture
                                                        , "RE: [{0}] {1}"
                                                        , (reader["Identifier"] != DBNull.Value) ?
                                                        reader["Identifier"].ToString()
                                                                : TicketUidUtil.Create(IncidentBox.Load((int)reader["IncidentBoxId"]).IdentifierMask, IncidentId)
                                                        , HttpUtility.HtmlDecode(reader["Title"].ToString())
                                                        );
                    }
                }
            }
            if (FileIds != "")
            {
                string sFiles = FileIds.Trim();
                if (sFiles.EndsWith(","))
                {
                    sFiles = sFiles.Substring(0, sFiles.Length - 1);
                }
                string[] masFiles = sFiles.Split(',');
                if (masFiles.Length > 0)
                {
                    string _containerName   = "FileLibrary";
                    string _containerKey    = "EMailAttach";
                    CS.BaseIbnContainer bic = CS.BaseIbnContainer.Create(_containerName, _containerKey);
                    CS.FileStorage      fs  = (CS.FileStorage)bic.LoadControl("FileStorage");

                    CS.BaseIbnContainer bic2 = CS.BaseIbnContainer.Create(FilesContainerName, FilesContainerKey);
                    CS.FileStorage      fs2  = (CS.FileStorage)bic.LoadControl("FileStorage");

                    CS.DirectoryInfo di = fs.GetDirectory(fs.Root.Id, _guid, true);
                    for (int i = 0; i < masFiles.Length; i++)
                    {
                        fs2.CopyFile(int.Parse(masFiles[i]), di.Id);
                    }
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "_getFiles",
                                                            "window.setTimeout('updateAttachments()', 500);", true);
                }
            }
            if (ErrorId != "")
            {
                string support_email = GlobalResourceManager.Strings["SupportEmail"];
                //if (Security.CurrentUser != null && Security.CurrentUser.Culture.ToLower().IndexOf("ru") >= 0)
                //    support_email = "*****@*****.**";
                txtTo.Text = support_email + "; ";

                txtSubject.Text = String.Format("{0} {1} {2} Error Report", IbnConst.CompanyName, IbnConst.ProductFamilyShort, IbnConst.VersionMajorDotMinor);

                string prefix   = Request.Url.Host.Replace(".", "_");
                string FilePath = Server.MapPath("../Admin/Log/Error/" + prefix + "_" + ErrorId + ".html");
                string sTemp    = String.Empty;
                using (StreamReader sr = File.OpenText(FilePath))
                {
                    sTemp += sr.ReadToEnd();
                }

                Match match = Regex.Match(sTemp, @"<body[^>]*>(?<HtmlBody>[\s\S]*?)</body>", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);
                if (match.Success)
                {
                    string body       = match.Groups["HtmlBody"].Value;
                    Match  matchStyle = Regex.Match(sTemp, @"<style[^>]*>(?<HtmlStyle>[\s\S]*?)</style>", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Multiline);
                    if (matchStyle.Success)
                    {
                        body += matchStyle.Value;
                    }
                    sTemp = body;
                }
                fckEditor.Text = sTemp;
            }
            if (lblCC.Text != "")
            {
                lblCCTitle.Text = LocRM.GetString("tTo") + ":";
                lblToTitle.Text = LocRM.GetString("tCc") + ":";
            }
        }