/*---------------------------------------------------------------------
* 			Copyright (C) 2024 TECHSCAN 版权所有。
*           www.techscan.cn
*┌──────────────────────────────────┐
*│　此技术信息为本公司机密信息，未经本公司书面同意禁止向第三方披露．　│
*│　版权所有：上海太迅自动识别技术有限公司 　 　　　　　　　　　　　　│
*└──────────────────────────────────┘
*
* 文件名：   MailKitHelp.cs
* 功能描述： N/A
* 作者：     26950
* CLR版本：  4.0.30319.42000
* 创建时间： 2024/3/14 12:24:08
* Client：   MAYONGLONG
* 文件版本： V1.0.0

===============================版本履历===============================
* Ver 		变更日期 				负责人 	变更内容
* V1.0.0	2024/3/14 12:24:08		Myl		Create
*
======================================================================
//--------------------------------------------------------------------*/

using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace TsSFCDeivceClient.Email
{
    public class MailKitHelp
    {

        /// <summary>
        /// 邮件发送状态
        /// </summary>
        public enum SendStatus
        {
            /// <summary>
            /// 默认,正常,准备发送
            /// </summary>
            Normal = 0,

            /// <summary>
            /// 发送成功
            /// </summary>
            Success = 1,

            /// <summary>
            /// 发送失败
            /// </summary>
            Failed = 2,

            /// <summary>
            /// 发送邮箱或收件邮箱未通过验证
            /// </summary>
            Unmatch = 3,

            /// <summary>
            /// 发件地址未通过验证
            /// </summary>
            SendMailAddressIsUnmatch = 4,

            /// <summary>
            /// 发件密码为空
            /// </summary>
            PassWordIsNull = 5,

            /// <summary>
            /// 收件地址未通过验证
            /// </summary>
            FromMailAddressIsUnmatch = 6
        }

        /// <summary>
        /// 发送标题和内容的字符集，默认是UTF8
        /// </summary>
        public Encoding CharSet = Encoding.UTF8;

        /// <summary>
        /// 设置指示邮件正文是否为 Html 格式
        /// 默认为False，不是Html格式
        /// </summary>
        public bool IsBodyHtml = false;

        /// <summary>
        /// 是否使用抄送
        /// </summary>
        public bool IsCC = false;

        /// <summary>
        /// 是否发送附件
        /// </summary>
        public bool IsSendAttachments = false;

        /// <summary>
        /// 是否开启安全套接字层 (SSL) 加密连接
        /// </summary>
        public bool IsSSL = false;

        /// <summary>
        /// SMTP服务器是否不需要身份认证
        /// 默认为False，需要使用账号和密码登陆
        /// </summary>
        public bool IsUseDefaultCredentials = false;

        /// <summary>
        /// 邮箱正则表达式(不区分大小写)，可修改成自定义正则表达式
        /// </summary>
        public string RegexText = @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

        /// <summary>
        /// Smtp 服务器端口,默认25
        /// </summary>
        public int SmtpPort = 25;


        /// <summary>
        /// 邮件附件
        /// 如果确定发送附件请将IsSendAttachments设置为true
        /// </summary>
        public List<MimePart> Attachments { get; set; }

        /// <summary>
        /// 邮件正文内容
        /// </summary>
        public string Body { get; set; }

        /// <summary>
        /// 邮件的抄送者
        /// 如果确定发送邮件的抄送者请将IsCC设置为true
        /// </summary>
        public string[] CarbonCopy { get; set; }

        /// <summary>
        /// 收件邮箱地址
        /// </summary>
        public string[] ToMailAddress { get; set; }

        /// <summary>
        /// 邮箱密码
        /// </summary>
        public string PassWord { get; set; }

        /// <summary>
        ///  发件邮箱地址
        /// </summary>
        public string FromMailAddress { get; set; }

        /// <summary>
        ///  发件邮箱昵称 ,默认为发件地址
        /// </summary>
        public string SendMailNickName { get; set; }

        /// <summary>
        /// Smtp 服务器地址
        /// </summary>
        public string SmtpAddress { get; set; }

        /// <summary>
        /// 邮件标题
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// 发送邮件，并且返回发送结果
        /// </summary>
        /// <returns></returns>
        public SendStatus Send(out string relustMessage)
        {
            relustMessage = string.Empty;

            #region 验证基本信息

            Regex reg = new Regex(this.RegexText, RegexOptions.IgnoreCase);
            if (!IsUseDefaultCredentials) // 使用账号密码登陆Smtp服务
            {
                if (!reg.IsMatch(this.FromMailAddress))
                {
                    relustMessage = "发件地址未通过验证";
                    return SendStatus.SendMailAddressIsUnmatch;
                }
                if (string.IsNullOrEmpty(this.PassWord))
                {
                    relustMessage = "发件密码为空";
                    return SendStatus.PassWordIsNull;
                }
            }

            if (this.ToMailAddress == null || this.ToMailAddress.Length <= 0)
            {
                relustMessage = "收件地址为空";
                return SendStatus.FromMailAddressIsUnmatch;
            }

            StringBuilder FailedELst = new StringBuilder();
            foreach (string item in this.ToMailAddress)
            {
                if (!reg.IsMatch(item))
                {
                    FailedELst.Append(Environment.NewLine + item);
                }
            }
            if (FailedELst.Length > 0)
            {
                relustMessage = "以下收件地址未通过验证:" + FailedELst;
                return SendStatus.FromMailAddressIsUnmatch;
            }

            #endregion 验证基本信息
            MimeMessage msg = new MimeMessage();
            msg.From.Add(new MailboxAddress(this.FromMailAddress, this.FromMailAddress));

            foreach (string t in ToMailAddress)
            {
                msg.To.Add(new MailboxAddress(t, t));
            }

            //抄送
            if (this.CarbonCopy != null && this.CarbonCopy.Length > 0 && this.IsCC) // 是否显示抄送
            {
                foreach (string item in this.CarbonCopy)
                {
                    msg.Cc.Add(new MailboxAddress(item, item));
                }
            }

            msg.Subject = this.Title; //邮件标题

            var bodyBuilder = new BodyBuilder();
            if (IsBodyHtml)
            {
                bodyBuilder.HtmlBody = this.Body;
            }
            else
            {
                bodyBuilder.TextBody = this.Body;
            }

            Multipart multipart = new Multipart("mixed")
            {
                bodyBuilder.ToMessageBody()
            };

            // 添加附件
            if (this.Attachments != null && this.Attachments.Count > 0 && this.IsSendAttachments)
            {
                foreach (MimePart item in this.Attachments)
                {
                    multipart.Add(item);
                }
            }

            msg.Body = multipart;
            string vSendMsg = "";
            SendStatus sendStatus = SendStatus.Normal;
            try
            {
                using (var client = new SmtpClient())
                {
                    client.CheckCertificateRevocation = false;
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    //smtp服务器，端口，是否开启ssl

                    client.Connect(SmtpAddress, SmtpPort, (IsSSL ? SecureSocketOptions.Auto : SecureSocketOptions.None));
                    if (!IsUseDefaultCredentials)
                        client.Authenticate(FromMailAddress, PassWord);

                    vSendMsg = client.Send(msg);
                    client.Disconnect(true);
                }
                relustMessage = $"邮件发送成功!{vSendMsg}";
                sendStatus = SendStatus.Success;
            }
            catch (Exception ee)
            {
                sendStatus = SendStatus.Failed;
                relustMessage = ee.InnerException == null ? ee.Message : ee.InnerException.ToString();
            }
            return sendStatus;
        }


        public string GetHtmlInfoString(string cMsg)
        {
            string lsMailFormatPath = string.Empty;

            lsMailFormatPath =

                Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Email"), "MailSuccess.html");
            //string.Format("{0}{1}", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Email"), "MailSuccess.html");
            string basicMailContent = "";
            using (StreamReader objReader = new StreamReader(lsMailFormatPath, Encoding.UTF8))
            {
                basicMailContent = objReader.ReadToEnd();
            }

            basicMailContent = basicMailContent.Replace("#SFC{{0}}SFC#", cMsg);
            return basicMailContent;
        }
    }
}
