MailService.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using Application.Abstractions.Messaging.Email;
  2. using Infrastructure.Persistence;
  3. using MailKit.Net.Smtp;
  4. using MailKit.Security;
  5. using Microsoft.EntityFrameworkCore;
  6. using Microsoft.Extensions.Logging;
  7. using Microsoft.Extensions.Options;
  8. using MimeKit;
  9. using SharedKernel;
  10. namespace Infrastructure.Messaging.Email
  11. {
  12. public class MailService : IMailService
  13. {
  14. private readonly AppSettings.SmtpSection _smtp;
  15. private readonly AppDbContext _db;
  16. private readonly ILogger<MailService> _logger;
  17. public MailService(IOptions<AppSettings> options, AppDbContext db, ILogger<MailService> logger)
  18. {
  19. _smtp = options.Value.SMTP;
  20. _db = db;
  21. _logger = logger;
  22. }
  23. public async Task SendAsync(SendData data, CancellationToken ct = default)
  24. {
  25. _logger.LogInformation("Sending email to {ToAddress} with subject {Subject}", data.ToAddress, data.Subject);
  26. var message = new MimeMessage();
  27. message.From.Add(new MailboxAddress(_smtp.FromName, _smtp.FromEmail));
  28. message.To.Add(MailboxAddress.Parse(data.ToAddress));
  29. message.Subject = data.Subject;
  30. var body = new BodyBuilder
  31. {
  32. HtmlBody = data.MessageHtml,
  33. TextBody = data.MessageText
  34. };
  35. message.Body = body.ToMessageBody();
  36. using var client = new SmtpClient();
  37. var secure = _smtp.UseStartTls ? SecureSocketOptions.StartTls : SecureSocketOptions.Auto;
  38. await client.ConnectAsync(_smtp.Host, _smtp.Port, secure, ct);
  39. if (!string.IsNullOrWhiteSpace(_smtp.User))
  40. {
  41. await client.AuthenticateAsync(_smtp.User, _smtp.Password, ct);
  42. }
  43. await client.SendAsync(message, ct);
  44. await client.DisconnectAsync(true, ct);
  45. _logger.LogInformation("Email sent to {ToAddress} with subject {Subject}", data.ToAddress, data.Subject);
  46. }
  47. }
  48. }