using MimeKit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using System.Configuration;
using SvetoforVKBot.App_Start;

namespace SvetoforVKBot.Services
{
    public class EmailService
    {
        public async Task SendEmailAsync(string email, string subject, string message)
        {
            var emailMessage = new MimeMessage();

            emailMessage.From.Add(new MailboxAddress(
                ((WebConfiguration)ConfigurationManager.GetSection("smtpClient")).FromName,
                ((WebConfiguration)ConfigurationManager.GetSection("smtpClient")).Email));
            emailMessage.To.Add(new MailboxAddress("", email));
            emailMessage.Subject = subject;
            emailMessage.Body = new TextPart(MimeKit.Text.TextFormat.Html)
            {
                Text = message
            };

            using (var client = new SmtpClient())
            {
                //await client.ConnectAsync("mail.hosting.reg.ru", 465);
                await client.ConnectAsync(
                    ((WebConfiguration)ConfigurationManager.GetSection("smtpClient")).Host, 
                    ((WebConfiguration)ConfigurationManager.GetSection("smtpClient")).Port,
                    (MailKit.Security.SecureSocketOptions)((WebConfiguration)ConfigurationManager.GetSection("smtpClient")).SSO);
                await client.AuthenticateAsync(
                    ((WebConfiguration)ConfigurationManager.GetSection("smtpClient")).UserName,
                    ((WebConfiguration)ConfigurationManager.GetSection("smtpClient")).Password);
                await client.SendAsync(emailMessage);
                await client.DisconnectAsync(true);
            }
        }
    }
}