EmailSender.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using Azure.Core;
  2. using Microsoft.AspNetCore.Identity.UI.Services;
  3. using Microsoft.Extensions.Options;
  4. using System.Net;
  5. using System.Net.Mail;
  6. using System.Threading.Tasks;
  7. namespace bitforum.Services
  8. {
  9. public class EmailSender : IEmailSender
  10. {
  11. private readonly ILogger _logger;
  12. private readonly string _smtpServer;
  13. private readonly int _smtpPort;
  14. private readonly string _fromEmail;
  15. private readonly string _emailPassword;
  16. public EmailSender(IConfiguration configuration, ILogger<EmailSender> logger)
  17. {
  18. var emailSettings = configuration.GetSection("EmailSettings");
  19. _smtpServer = emailSettings["SmtpServer"];
  20. _smtpPort = int.Parse(emailSettings["SmtpPort"]);
  21. _fromEmail = emailSettings["FromEmail"];
  22. _emailPassword = emailSettings["EmailPassword"];
  23. _logger = logger;
  24. }
  25. public async Task SendEmailAsync(string email, string subject, string message)
  26. {
  27. try
  28. {
  29. var client = new SmtpClient(_smtpServer, _smtpPort)
  30. {
  31. Credentials = new NetworkCredential(_fromEmail, _emailPassword),
  32. EnableSsl = true
  33. };
  34. var mailMessage = new MailMessage
  35. {
  36. From = new MailAddress(_fromEmail),
  37. Subject = subject,
  38. Body = message,
  39. IsBodyHtml = true
  40. };
  41. mailMessage.To.Add(email);
  42. _logger.LogInformation($"Sending email to {email} with subject {subject}.");
  43. await client.SendMailAsync(mailMessage);
  44. _logger.LogInformation($"Email sent successfully to {email}.");
  45. }
  46. catch (SmtpException smtpEx)
  47. {
  48. Console.WriteLine($"SMTP error: {smtpEx.Message}");
  49. _logger.LogError($"SMTP error: {smtpEx.StatusCode} - {smtpEx.Message}");
  50. throw;
  51. }
  52. catch (Exception ex)
  53. {
  54. Console.WriteLine($"Email sending failed: {ex.Message}");
  55. _logger.LogError($"Failed to send email to {email}: {ex.Message}");
  56. throw;
  57. }
  58. }
  59. }
  60. }