using Furion;
using Furion.FriendlyException;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using System;
using System.Net.Mail;
using System.Text;

namespace Ewide.Core.Util
{
    public class MailHelper
    {
        public string Message { set; get; }
        public string UserMailAddress { set; get; }
        /// <summary>
        /// 邮箱类
        /// </summary>
        /// <param name="message">发送的信息</param>
        /// <param name="userMailAddress">用户的地址</param>
        public MailHelper(string message, string userMailAddress)
        {
            //MailHelper mail = new MailHelper("第一次发送邮箱测试", "591410538@qq.com");
            //mail.Send();
            Message = message;
            UserMailAddress = userMailAddress;
        }
        public void Send()
        {
            string account = App.Configuration["Mail:Account"];
            string passWord = App.Configuration["Mail:PassWord"];
            //var options = Options.Create(options: new MemoryCacheOptions());
            //IMemoryCache cache = new MemoryCache(options);
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Host = App.Configuration["Mail:Host"];
            smtpClient.Credentials = new System.Net.NetworkCredential(account, passWord);
            smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

            MailMessage mailMessage = new MailMessage();
            MailAddress fromAddr = new MailAddress(account);
            mailMessage.From = fromAddr;
            mailMessage.To.Add(UserMailAddress);
            mailMessage.Subject = App.Configuration["Mail:Subject"];
            mailMessage.BodyEncoding = Encoding.UTF8;
            mailMessage.IsBodyHtml = true;
            mailMessage.Priority = MailPriority.Low;
            mailMessage.Body = Message;
            try
            {
                smtpClient.Send(mailMessage);
            }
            catch 
            {
                throw Oops.Oh(ErrorCode.xg1100);
            }
        }
    }
}
