using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TABS.MailCarrier.AuxLib;
using TABS.MailCarrier.WebSDK;
using TABS.MailCarrier.WebSDK.Calendar;
using TABS.MailCarrier.WebSDK.Calendar.iCalendar;
using TABS.MailCarrier.WebSDK.Mail;
using TABS.MailCarrier.WebSDK.User;

/// <summary>
/// View.aspx 파라미터 
///   msg (필수, GUID) - 메시지 ID
///   folder (선택, GUID) - 폴더 ID, 없을 경우 AllMails 폴더
///   page (선택) - 페이지 번호(0에서 시작)
///   searchCategoty (선택) - 검색 카테고리(subject, author, content)
///   searchKeyword (선택) - 검색 키워드
/// </summary>
public partial class Mail_View : System.Web.UI.Page
{
    private const int MAX_RECIPIENTS = 10;      // 최대 수신자 출력 수

    protected Guid _msgId;                      // 메시지 ID
    protected Guid _folderId;                   // 폴더 ID
    protected string _folderType;               // 메일박스 타입 (ex. mcInbox, mcSent ..)
    protected string _folderName;               // 메일박스 폴더 이름 (ex. mcInbox, mcSent, mcAllMails, 사용자정의 ...)
    protected string _page;
    protected string _searchCategoty;
    protected string _searchKeyword;
    protected string _listPageParams;

    protected string _ccCssClass = "";          // 참조 영역 class 값
    protected string _bccCssClass = "";         // 숨은 참조 영역 class 값
    protected string _attachCssClass = "";      // 첨부 영역 class 값
    protected int _msgFlagValue = 0;            // 메시지 플래그 값
    protected Guid _prevMsgId = Guid.Empty;     // 이전 메시지 ID
    protected Guid _nextMsgId = Guid.Empty;     // 이전 메시지 ID

    protected string _showMeetingReq = "false"; // Meeting Request 창 열기

    [Flags]
    protected enum LoadFlag : int
    {
        CheckOwner = 0x0001,                    // 메시지 소유자 검사
        SetReadMark = 0x0002                    // 메시지 읽음 표시
    }

    protected override void InitializeCulture()
    {
        string defLang = WebUser.CurrentUser.UiLanguage;
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(defLang);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(defLang);
        base.InitializeCulture();
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        WebUtil.SetMcCommonCss(Page.Header);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        _msgId = WebParam.GetGuidParamValue("msg");
        if (_msgId == Guid.Empty) return;
        _page = WebParam.GetStrParamValue("page");
        _searchCategoty = WebParam.GetStrParamValue("searchCategoty");
        _searchKeyword = WebParam.GetStrParamValue("searchKeyword");        

        if (!IsPostBack)
        {
            Page.Title = AppSetting.GetTitleInfo(Request).Title;

            _folderId = WebParam.GetGuidParamValue("folder");
            if (_folderId == Guid.Empty) _folderId = MailUtil.AllMails;

            if (_folderId == MailUtil.AllMails)
            {
                _folderType = Mailbox.INBOX;
                _folderName = MailUtil.AllMailsMailboxName;
            }
            else if (_folderId == MailUtil.UnreadMails)
            {
                _folderType = Mailbox.INBOX;
                _folderName = MailUtil.UnreadMailsMailboxName;
            }
            else if (_folderId == MailUtil.FlaggedMails)
            {
                _folderType = Mailbox.INBOX;
                _folderName = MailUtil.FlaggedMailsMailboxName;
            }
            else
            {
                TABS.MailCarrier.WebSDK.Mail.MailboxFolder folder = new TABS.MailCarrier.WebSDK.Mail.MailboxFolder(_folderId);
                _folderType = GetMailboxName(_folderId, out _folderName);
            }

            LoadMailMessage(_msgId, "auto", LoadFlag.CheckOwner | LoadFlag.SetReadMark);

            if (!AppSetting.EnableSpamReport) BootstrapUtil.VisibleControl(spamButton, false);

            ViewState["folderId"] = _folderId;             // 폴더 ID가 지정되어 있지 않을 경우 처음 1회만 쿼리하기 위해 저장
            ViewState["folderType"] = _folderType;
            ViewState["folderName"] = _folderName;
        }
        else
        {
            _folderId = (Guid)ViewState["folderId"];
            _folderType = (string)ViewState["folderType"];
            _folderName = (string)ViewState["folderName"];
        }

        _listPageParams = string.Format("folder={0}&page={1}&searchCategoty={2}&searchKeyword={3}", _folderId, _page, _searchCategoty, Server.UrlEncode(_searchKeyword));
    }

    // Ajax 호출 방식으로 변경되어 사용되지 않는다.
    protected void DeleteButton_Click(object sender, EventArgs e)
    {
        Message message = new Message(_msgId);
        if (_folderType == Mailbox.SPAMBOX || _folderType == Mailbox.TRASHBOX)
        {
            message.Remove();
            WebOperationLog.Write(WebUser.CurrentUser.MailAddress, Request.UserHostAddress, "M/Mail/View.aspx", "RemoveMessage", string.Format("{0}(msg:{1})", _folderType, message.ID));
        }
        else
        {
            message.MoveToTrash(WebUser.CurrentUser.DomainUserID);
            WebOperationLog.Write(WebUser.CurrentUser.MailAddress, Request.UserHostAddress, "M/Mail/View.aspx", "MsgMoveToTrash", string.Format("{0}(msg:{1})", _folderType, message.ID));
        }
        Response.Redirect(string.Format("List.aspx?folder={0}&page={1}", _folderId.ToString(), _page), true);
    }

    /// <summary>
    /// 메일 메시지를 로딩한다.
    /// </summary>
    /// <param name="msgId">로딩할 메시지 ID</param>
    /// <param name="charset">메시지 디코딩시 사용될 문자셋</param>
    /// <param name="loadFlag">로딩시 처리할 동작 플래그</param>
    private void LoadMailMessage(Guid msgId, string charset, LoadFlag loadFlag)
    {
        Message message = new Message(msgId);

        // msg가 본인 소유의 것인지 검사한다.
        if ((loadFlag & LoadFlag.CheckOwner) > 0)
        {
            if (!message.IsMine(WebUser.CurrentUser.DomainUserID))
            {
                Response.Redirect("~/Error.aspx?code=2", true);
                return;
            }
        }

        try
        {
            message.Charset = charset;
            message.Load();

            // 스팸정보를 출력한다.
            ShowSpamInformation(message);
            ShowSecurityInformation(message);

            // 메시지를 출력한다.
            ShowMailMessage(message, message.ID);

            // 이전 메시지와 다음 메시지의 기본 정보를 출력한다.
            ShowPrevAndNextMailMessageHeader(message);

            MakeSpamReportModal(message);

            if ((loadFlag & LoadFlag.SetReadMark) > 0)
            {
                // 새 메시지일 경우 읽음으로 표시한다.
                message.SetReadStatus(true);
            }

        }
        catch (LoadFailException)
        {
        }
    }

    private void ShowSpamInformation(Message message)
    {
        if ((message.ActionFlag & Message.MsgActionFlag.Spam) > 0)
        {
            string spamHeader = message.GetHeader("X-MC-Spam");
            string spamLabel = spamHeader;
            spamHeader = spamHeader.ToLower();
            string spamDesc = "";
            if (spamHeader.IndexOf("dmarc") != -1)
                spamDesc = string.Format(Resources.Mail.Spam_Dmarc, message.FromAddress);
            else if (spamHeader.IndexOf("spf") != -1)
                spamDesc = string.Format(Resources.Mail.Spam_Spf, message.FromAddress);
            else if (spamHeader.IndexOf("spamassassin") != -1)
                spamDesc = Resources.Mail.Spam_SpamAssassin;
            else if (spamHeader.IndexOf("inconsist") != -1)
                spamDesc = Resources.Mail.Spam_Consist;
            else if (spamHeader.IndexOf("unsafe attach") != -1)
                spamDesc = Resources.Mail.Spam_UnsafeAttach;
            else if (spamHeader.IndexOf("vba attach") != -1)
                spamDesc = Resources.Mail.Spam_VbaAttach;
            else if (spamHeader.IndexOf("charser") != -1)
                spamDesc = Resources.Mail.Spam_Charset;
            else if (spamHeader.IndexOf("no subject") != -1)
                spamDesc = Resources.Mail.Spam_NoSubject;
            else if (spamHeader.IndexOf("max size") != -1)
                spamDesc = Resources.Mail.Spam_MaxSize;
            else if (spamHeader.IndexOf("mail from") != -1)
                spamDesc = Resources.Mail.Spam_MailFrom;
            else if (spamHeader.IndexOf("sender") != -1)
                spamDesc = Resources.Mail.Spam_Sender;
            else if (spamHeader.IndexOf("subject") != -1)
                spamDesc = Resources.Mail.Spam_Subject;
            else if (spamHeader.IndexOf("content") != -1)
                spamDesc = Resources.Mail.Spam_Content;
            else if (spamHeader.IndexOf("attach") != -1)
                spamDesc = Resources.Mail.Spam_Attach;
            else if (spamHeader.IndexOf("virus") != -1)
                spamDesc = Resources.Mail.Spam_Virus;
            else if (spamHeader.IndexOf("dkim") != -1)
                spamDesc = string.Format(Resources.Mail.Spam_Dkim, message.FromAddress);
            else if (spamHeader.IndexOf("black list") != -1)
                spamDesc = Resources.Mail.Spam_BlackList;
            else
            {
                spamLabel = "";
                spamDesc = Resources.Mail.Spam_NoInfoDesc;
            }

            string spamMsg = (spamLabel != "") ? string.Format("{0}<br />[{1}]", spamDesc, spamLabel) : spamDesc;            
            SpamLiteral.Text = string.Format("<div class=\"row\"><div class=\"col-xs-12\"><div class=\"alert alert-danger\">{0}</div></div></div>", spamMsg);
        }
    }

    private void ShowSecurityInformation(Message message)
    {
        // 스팸 메일은 보안 정보를 출력하지 않는다.
        if ((message.ActionFlag & Message.MsgActionFlag.Spam) > 0) return;

        List<string> securityLabelList = new List<string>();

        // 발신자 메일 주소 사칭()을 확인해 출력한다.
        string forgeAddrInfo = message.GetHeader("X-MC-SpoofFrom");
        if (forgeAddrInfo.Length > 0)
        {
            string[] favalues = forgeAddrInfo.Split(new char[] { ';' });
            if (favalues[0] == "safelist")
            {
                securityLabelList.Add(string.Format(GetLocalResourceObject("SecWarn_MailFrom3").ToString(), message.FromAddress, favalues[1]));
            }
            else if (favalues[0] == "contact")
            {
                securityLabelList.Add(string.Format(GetLocalResourceObject("SecWarn_MailFrom4").ToString(), message.FromAddress, favalues[1]));
            }
        }

        // SPF 검증 정보를 확인해 출력한다.
        Message.HeaderAttributes spfAttrs = message.X_Mc_Spf;
        if (spfAttrs.GetValue("pass") == "n" && spfAttrs.GetValue("nospf") == "n")
        {
            string domain = spfAttrs.GetValue("d");
            securityLabelList.Add(string.Format(GetLocalResourceObject("SecWarn_Spf").ToString(), domain));
        }

        // DKIM 검증 정보를 확인해 출력한다.
        Message.HeaderAttributes dkimAttrs = message.X_Mc_Dkim;
        if (dkimAttrs.GetValue("v") == "n")
        {
            string status = dkimAttrs.GetValue("s");
            if (status == "fail")
            {
                string domain = dkimAttrs.GetValue("d");
                securityLabelList.Add(string.Format(GetLocalResourceObject("SecWarn_Dkim").ToString(), domain));
            }
        }

        // 발송자 도메인 일치성을 확인해 출력한다.
        Message.HeaderAttributes smtpAttrs = message.X_Mc_Smtp;
        string mailFromDomain = smtpAttrs.GetValue("d");
        if (mailFromDomain != "")
        {
            string headerFromDomain = message.FromAddress.Substring(message.FromAddress.IndexOf('@') + 1).ToLower();
            if (mailFromDomain.ToLower().IndexOf(headerFromDomain) == -1)
            {
                securityLabelList.Add(string.Format(GetLocalResourceObject("SecWarn_MailFrom0").ToString(), mailFromDomain));
            }
            else
            {
                // 발송자 메일 주소 일치성을 확인해 출력한다.
                string f = smtpAttrs.GetValue("f");
                if (f.Length > 0)
                {
                    string mailFrom = string.Format("{0}@{1}", f, smtpAttrs.GetValue("d"));
                    string headerFrom = message.FromAddress;
                    if (string.Compare(mailFrom, headerFrom, true) != 0 && string.Compare(f, "x-mc-bcc", true) != 0)
                    {
                        securityLabelList.Add(string.Format(GetLocalResourceObject("SecWarn_MailFrom1").ToString(), mailFrom));
                    }
                }
            }
        }

        // 보낸 사람 이름에 메일 주소가 있을 경우 속임을 위한 것인지 검사한다.
        Regex regEx = new Regex(MailUtil.EmailPattern, RegexOptions.IgnoreCase);
        Match m = regEx.Match(message.FromName);
        if (m.Success)
        {
            if (string.Compare(m.Value, message.FromAddress, true) != 0)
            {
                securityLabelList.Add(string.Format(GetLocalResourceObject("SecWarn_MailFrom2").ToString(), m.Value, message.FromAddress));
            }
        }

        if (securityLabelList.Count > 0)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in securityLabelList)
            {
                sb.Append(string.Format("<li>{0}</li>", s));
            }
            SecWarnLiteral.Text = string.Format("<div class=\"row\"><div class=\"col-xs-12\"><div class=\"alert alert-warning\"><ul style='padding-left:8px;'>{0}</ul></div></div></div>", sb.ToString());
        }
    }

    /// <summary>
    /// 메일 메시지를 출력한다.
    /// </summary>
    /// <param name="message"></param>
    private void ShowMailMessage(Message message, Guid msgId)
    {
        // 제목 출력
        SubjectLabel.Text = message.Subject;

        // 플래그 출력        
        _msgFlagValue = message.Flag;
        if (_msgFlagValue >= 0 && _msgFlagValue <= 6)
        {
            string[] colors = { "#CECEC6", "#D3401B", "#638CD6", "#F4DE84", "#94C673", "#F78431", "#B563D6" };
            FlagIcon.Attributes["class"] = "fa-solid fa-flag mc-likeLink";
            FlagIcon.Attributes["style"] = string.Format("color:{0}", colors[_msgFlagValue]);
        }
        else
        {
            FlagIcon.Attributes["class"] = "fa-solid fa-check mc-likeLink";
            FlagIcon.Attributes["style"] = "color:#524A52";
        }

        // 보낸 사람 출력
        FromAddrLabel.Text = MailUtil.GetMailFromString4Html(message.FromName, message.FromAddress);

        // 받는 사람 출력
        ToAddrTag.Text = MailUtil.GetRecipientsString4Html(message.To, MAX_RECIPIENTS);
        
        // 참조 출력
        CcAddrTag.Text = MailUtil.GetRecipientsString4Html(message.Cc, MAX_RECIPIENTS);
        _ccCssClass = (CcAddrTag.Text.Length == 0) ? "collapse" : "";

        // 본인이 보낸 메시지에 대해서만 숨은 참조를 출력한다.
        if ((message.ActionFlag & Message.MsgActionFlag.Sent) > 0)
        {
            BccAddrTag.Text = GetBccRecipientString(message.UserDefinedXml);
        }
        _bccCssClass = (BccAddrTag.Text.Length == 0) ? "collapse" : "";

        // 받은 날짜 출력 - Date 부분이 잘못 구성된 메시지가 있으므로 예외를 처리한다.
        try
        {
            RecvDateLabel.Text = string.Format("{0:f}", WebUser.CurrentUser.ToLocalTime(message.SentTime));
        }
        catch
        {
            RecvDateLabel.Text = message.GetHeader("Date");
        }

        // 첨부 파일 출력
        int attachCount = 0, attachSize = 0;
        bool relatedAttach = false;
        if (message.Attachments.Length > 0)
        {
            ExtIconMap extIconMap = new ExtIconMap();
            StringBuilder attchSb = new StringBuilder();
            foreach (Attachment attach in message.Attachments)
            {
                if (attach.ContentType == "message/rfc822")
                {
                    string item = (!attach.Deleted) ?
                        string.Format("<a href='#' class='list-group-item' onclick='OpenViewEmlWindow(\"{1}\")'><img src='../Images/Ext/{0}'/>{2} ({3})</a>",
                            extIconMap.GetIconName(attach.FilePath), Server.UrlEncode(attach.FilePath), attach.FileName, WebUtil.GetFormattedFileSize(attach.Size)) :
                        string.Format("<div class='list-group-item'><img src='../Images/Ext/{0}'/><del>{1} ({2})</del></div>",
                            extIconMap.GetIconName(attach.FilePath), attach.FileName, WebUtil.GetFormattedFileSize(attach.Size));

                    attchSb.Append(item);
                    attachCount++;
                    attachSize += attach.Size;
                }
                else if (attach.ContentID != "" && message.HtmlBody.IndexOf(attach.ContentID) > 0)
                {
                    relatedAttach = true;
                }
                else if (attach.ContentType == "text/calendar")
                {
                    if (_folderType != Mailbox.TEMPBOX && _folderType != Mailbox.SENTBOX && _folderType != Mailbox.SPAMBOX && MqWriterLabel.Text.Length == 0)
                    {
                        string webTempPath = GlobalConfig.WebShareTempPath;
                        iCalendar cal = new iCalendar();
                        cal.LoadFile(webTempPath + "\\" + attach.FilePath, false);
                        if (cal.Method == "REQUEST")
                        {
                            _showMeetingReq = "true";
                            MqSubjectLabel.Text = cal.Summary;
                            MqPlaceLabel.Text = cal.Location;
                            MqWriterLabel.Text = cal.OrganizerName;
                            if (cal.AllDayEvent)
                            {
                                MqBeginDateLabel.Text = Resources.Calendar.AllDay2;
                            }
                            else
                            {
                                MqBeginDateLabel.Text = cal.DtStart.ToString("f");
                                MqEndDateLabel.Text = cal.DtEnd.ToString("f");
                            }
                        }
                    }
                }
                else
                {
                    // 잘못 구성된 인라인 파일이더라도 ContentID만 존재하면 HTML 구성시 인라인이 처리될 수 있도록 relatedAttach = true로 지정한다.
                    //  - ContentID가 존재하고 attachment로 명시되어 있지만 실제는 inline으로 사용되는 메시지가 있다.
                    if (attach.ContentID != "") relatedAttach = true;

                    string item = (!attach.Deleted) ?
                        string.Format("<a href='Download.ashx?file={1}&name={2}' class='list-group-item'><img src='../Images/Ext/{0}'/>{3} ({4})</a>",
                            extIconMap.GetIconName(attach.FilePath), attach.FilePath, Server.UrlEncode(attach.FileName), attach.FileName, WebUtil.GetFormattedFileSize(attach.Size)) :
                        string.Format("<div class='list-group-item'><img src='../Images/Ext/{0}'/><del>{1} ({2})</del></div>",
                            extIconMap.GetIconName(attach.FilePath), attach.FileName, WebUtil.GetFormattedFileSize(attach.Size));
                    attchSb.Append(item);
                    attachCount++;
                    attachSize += attach.Size;

                    if (attach.ContentType == "application/ms-tnef" && !attach.Deleted)
                    {
                        if (AppSetting.SupportParseTNEF)
                        {
                            string webTempPath = GlobalConfig.WebShareTempPath;
                            TnefParser tnefParser = new TnefParser();
                            List<TnefAttachFile> tnefAttachments = tnefParser.Parse(webTempPath + "\\" + attach.FilePath, webTempPath, msgId.ToString());
                            foreach (TnefAttachFile tnefAttach in tnefAttachments)
                            {
                                item = string.Format("<a href='#' class='list-group-item'><img src='../Images/Ext/{0}'/>TNEF_{3} ({4})</a>",
                                        extIconMap.GetIconName(tnefAttach.FileName), tnefAttach.SaveName,
                                        Server.UrlEncode(tnefAttach.FileName), tnefAttach.FileName, WebUtil.GetFormattedFileSize(tnefAttach.FileSize));
                                attchSb.Append(item);
                                attachCount++;
                                attachSize += attach.Size;
                            }
                        }
                    }
                }
            }
            AttachListTag.Text = attchSb.ToString();
        }
        _attachCssClass = (attachCount > 0) ? "collapse in" : "collapse";
        AttachSummaryLabel.Text = string.Format(GetLocalResourceObject("AttachSummary").ToString(), attachCount, WebUtil.GetFormattedFileSize((long)attachSize));

        // 본문 출력
        if (message.HtmlBody != "")
        {
            // <body>에 있는 스타일 등을 제거하기 위해 <body></body>를 제거한다.
            HtmlStripper htmlStripper = new HtmlStripper();
            string html = htmlStripper.StripBodyTag(message.HtmlBody, true);

            if (relatedAttach)
            {
                Array.Sort<Attachment>(message.Attachments, new Comparison<Attachment>((i1, i2) => i2.ContentID.CompareTo(i1.ContentID)));
                foreach (Attachment attach in message.Attachments)
                {
                    if (attach.ContentID != "")
                    {
                        string cid = "cid:" + attach.ContentID;
                        string downlink = "Download.ashx?content=" + attach.FilePath;
                        html = html.Replace(cid, downlink);
                    }
                }
            }
            MsgBodyHolder.Controls.Add(new LiteralControl(html));
        }
        else
        {
            string html = WebUtil.GetFormattedPlainText(message.TextBody, true);
            MsgBodyHolder.Controls.Add(new LiteralControl(html));
        }
    }

    private void ShowPrevAndNextMailMessageHeader(Message message)
    {
        if (_folderId == MailUtil.AllMails || _folderId == MailUtil.UnreadMails || _folderId == MailUtil.FlaggedMails)
        {
            UserMailbox userMbox = new UserMailbox(WebUser.CurrentUser.DomainUserID);
            userMbox.GetPrevNextMessageID(_msgId, out _prevMsgId, out _nextMsgId);
        }
        else
        {
            TABS.MailCarrier.WebSDK.Mail.MailboxFolder folder = new TABS.MailCarrier.WebSDK.Mail.MailboxFolder(_folderId);
            folder.GetPrevNextMessageID(_msgId, out _prevMsgId, out _nextMsgId);
        }

        if (_nextMsgId == Guid.Empty) 
        {
            BootstrapUtil.EnableButton(nextToolButton, false);
        }
        if (_prevMsgId == Guid.Empty)
        {
            BootstrapUtil.EnableButton(prevToolButton, false);
        }
    }

    private void MakeSpamReportModal(Message message)
    {
        bool canbeReported = false;
        string mcSmtp = message.GetHeader("X-MC-Smtp");
        string mcSpam = message.GetHeader("X-MC-Spam").ToUpper();
        string mcSystem = message.GetHeader("X-MC-MsgType").ToUpper();
        if (!MaintenanceLicenseCheck.IsValid() || mcSpam == "SPAMOUT EXPIRED" || mcSpam == "SPAMAS EXPIRED")
        {
            // 유지보수 라이센스가 만료
            SpamLabel1.Text = GetLocalResourceObject("SR_Msg01").ToString();
            SpamLabel2.Text = GetLocalResourceObject("SR_Msg02").ToString();
        }
        else if (mcSpam == "SPAMOUT OFF" || mcSpam == "SPAMAS OFF")
        {
            // 스팸엔진 OFF
            SpamLabel1.Text = GetLocalResourceObject("SR_Msg01").ToString();
            SpamLabel2.Text = GetLocalResourceObject("SR_Msg03").ToString();
        }
        else if (mcSpam != "")
        {
            // 스팸으로 판별된 경우
            mcSpam = message.GetHeader("X-MC-Spam");
            SpamLabel1.Text = GetLocalResourceObject("SR_Msg01").ToString();
            SpamLabel2.Text = string.Format(GetLocalResourceObject("SR_Msg04").ToString(), mcSpam);
        }
        else if (mcSystem == "SYSTEM")
        {
            // 시스템에서 발송된 메일인 경우
            SpamLabel1.Text = GetLocalResourceObject("SR_Msg01").ToString();
            SpamLabel2.Text = GetLocalResourceObject("SR_Msg05").ToString();
        }
        else if (mcSmtp.IndexOf("relay=y;") >= 0)
        {
            // 릴레이 허용 IP에서 발송된 메일
            SpamLabel1.Text = GetLocalResourceObject("SR_Msg01").ToString();
            SpamLabel2.Text = GetLocalResourceObject("SR_Msg08-1").ToString();
        }
        else if (mcSmtp.IndexOf("auth=y;") >= 0)
        {
            // 인증된 사용자가 발송한 메일
            SpamLabel1.Text = GetLocalResourceObject("SR_Msg01").ToString();
            SpamLabel2.Text = GetLocalResourceObject("SR_Msg08-2").ToString();
        }
        else if (mcSmtp.IndexOf("nospam=y;") >= 0)
        {
            // 도메인 예외 정책(IP, 도메인)에 따라 스팸 검사를 하지 않은 메일
            SpamLabel1.Text = GetLocalResourceObject("SR_Msg01").ToString();
            SpamLabel2.Text = GetLocalResourceObject("SR_Msg08-3").ToString();
        }
        else
        {
            canbeReported = true;
        }

        if (!canbeReported)
        {
            spamReportOkButton.Attributes.Add("disabled", "disabled");
        }

        BlockMailLabel.Text = Server.HtmlEncode(message.FromAddress);
        int pos = message.FromAddress.IndexOf('@');
        if (pos > 0) 
        {
            BlockDomainLabel.Text = Server.HtmlEncode(message.FromAddress.Substring(pos));
        }
    }

    /// <summary>
    /// folderId를 가지고 메일박스 이름을 가져온다.
    /// </summary>
    /// <param name="folderId"></param>
    /// <returns></returns>
    private string GetMailboxName(Guid folderId, out string folderName)
    {
        TABS.MailCarrier.WebSDK.Mail.MailboxFolder folder = new TABS.MailCarrier.WebSDK.Mail.MailboxFolder(folderId);
        folderName = folder.Name;
        TABS.MailCarrier.WebSDK.Mail.Mailbox mailbox = new TABS.MailCarrier.WebSDK.Mail.Mailbox(folder.MailboxID);
        return mailbox.Name;
    }

    private string GetBccRecipientString(string userDefinedXml)
    {
        if (userDefinedXml != "")
        {
            RecipientCollection bccList = new RecipientCollection();

            MsgExtender extender = new MsgExtender();
            extender.LoadFromXml(userDefinedXml);
            foreach (RcptItem item in extender.RcptItems)
            {
                if (item.Type == "bcc")
                {
                    if (item.Source == "email")
                        bccList.Add(new Recipient(item.Name, item.Value));
                    else
                        bccList.Add(new Recipient(item.Name, ""));
                }
            }
            if (bccList.Count > 0)
            {
                return MailUtil.GetRecipientsString4Html(bccList.ToArray(), MAX_RECIPIENTS);
            }
        }
        return "";
    }
}