using Microsoft.Extensions.Configuration;
using System.Net;
using System.Net.Mail;
using System.Text;

namespace Long.Utils.Mail;

/// <summary>
/// 发送邮件
/// </summary>
public class EMail
{
    private readonly IConfiguration configuration;

    private readonly EMailOption eMailOption;

    public EMail()
    {
        IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

        configuration = configurationBuilder.Build();

        eMailOption = new EMailOption();
        var section = configuration.GetSection("EMailOption");
        eMailOption.Server = section.GetSection("Server").Value ?? "";
        var postString = section.GetSection("Port").Value;
        if (postString != null)
        {
            eMailOption.Port = int.Parse(postString ?? "");
        }
        eMailOption.UserName = section.GetSection("UserName").Value ?? "";
        eMailOption.Password = section.GetSection("Password").Value ?? "";
        eMailOption.From = section.GetSection("From").Value ?? "";
    }

    /// <summary>
    /// 发送
    /// </summary>
    /// <param name="subject">主题</param>
    /// <param name="message">内容</param>
    /// <param name="address">收件地址</param>
    /// <exception cref="ApplicationException"></exception>
    public async Task Send(string subject, string message, string address)
    {
        var client = new SmtpClient();
        var mailMsg = new MailMessage();

        client.Host = eMailOption.Server;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.EnableSsl = true;

        mailMsg.To.Add(new MailAddress(address));
        mailMsg.From = new MailAddress(eMailOption.From);
        mailMsg.SubjectEncoding = Encoding.UTF8;
        mailMsg.Subject = subject;
        mailMsg.BodyEncoding = Encoding.UTF8;
        mailMsg.Body = message;

        try
        {
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(eMailOption.UserName, eMailOption.Password);

            // 发送邮件
            await client.SendMailAsync(mailMsg);
            client.Dispose();
        }
        catch (Exception ex)
        {
            throw new ApplicationException(ex.Message);
        }
    }
}