using Azure.Core; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.Extensions.Options; using System.Net; using System.Net.Mail; using System.Threading.Tasks; namespace bitforum.Services { public class EmailSender : IEmailSender { private readonly ILogger _logger; private readonly string _smtpServer; private readonly int _smtpPort; private readonly string _fromEmail; private readonly string _emailPassword; public EmailSender(IConfiguration configuration, ILogger logger) { var emailSettings = configuration.GetSection("EmailSettings"); _smtpServer = emailSettings["SmtpServer"]; _smtpPort = int.Parse(emailSettings["SmtpPort"]); _fromEmail = emailSettings["FromEmail"]; _emailPassword = emailSettings["EmailPassword"]; _logger = logger; } public async Task SendEmailAsync(string email, string subject, string message) { try { var client = new SmtpClient(_smtpServer, _smtpPort) { Credentials = new NetworkCredential(_fromEmail, _emailPassword), EnableSsl = true }; var mailMessage = new MailMessage { From = new MailAddress(_fromEmail), Subject = subject, Body = message, IsBodyHtml = true }; mailMessage.To.Add(email); _logger.LogInformation($"Sending email to {email} with subject {subject}."); await client.SendMailAsync(mailMessage); _logger.LogInformation($"Email sent successfully to {email}."); } catch (SmtpException smtpEx) { Console.WriteLine($"SMTP error: {smtpEx.Message}"); _logger.LogError($"SMTP error: {smtpEx.StatusCode} - {smtpEx.Message}"); throw; } catch (Exception ex) { Console.WriteLine($"Email sending failed: {ex.Message}"); _logger.LogError($"Failed to send email to {email}: {ex.Message}"); throw; } } } }