|
| 1 | +using System.Text; |
| 2 | +using System.Text.Json; |
| 3 | + |
| 4 | +namespace ControleContatos.Services; |
| 5 | + |
| 6 | +public class BrevoEmailSender : IEmailSender |
| 7 | +{ |
| 8 | + private readonly IHttpClientFactory _httpClientFactory; |
| 9 | + private readonly IConfiguration _config; |
| 10 | + private readonly ILogger<BrevoEmailSender> _logger; |
| 11 | + private readonly IWebHostEnvironment _env; |
| 12 | + |
| 13 | + public BrevoEmailSender( |
| 14 | + IHttpClientFactory httpClientFactory, |
| 15 | + IConfiguration config, |
| 16 | + ILogger<BrevoEmailSender> logger, |
| 17 | + IWebHostEnvironment env) |
| 18 | + { |
| 19 | + _httpClientFactory = httpClientFactory; |
| 20 | + _config = config; |
| 21 | + _logger = logger; |
| 22 | + _env = env; |
| 23 | + } |
| 24 | + |
| 25 | + public async Task SendEmailAsync(string toEmail, string subject, string htmlBody) |
| 26 | + { |
| 27 | + var apiKey = _config["Bravo:APIKey"] ?? ""; |
| 28 | + var fromEmail = _config["Bravo:From"] ?? _config["EmailSettings:FromEmail"] ?? ""; |
| 29 | + var fromName = _config["EmailSettings:FromName"] ?? "ControleContatos"; |
| 30 | + |
| 31 | + if (string.IsNullOrWhiteSpace(apiKey)) |
| 32 | + { |
| 33 | + _logger.LogWarning("[Brevo] API Key não configurada. E-mail NÃO enviado. To={To}, Subject={Subject}", toEmail, subject); |
| 34 | + if (_env.IsDevelopment()) |
| 35 | + _logger.LogInformation("[Brevo][DEV] Conteúdo:\nPara: {To}\nAssunto: {Subject}\nCorpo:\n{Body}", toEmail, subject, htmlBody); |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + var payload = new |
| 40 | + { |
| 41 | + sender = new { name = fromName, email = fromEmail }, |
| 42 | + to = new[] { new { email = toEmail } }, |
| 43 | + subject, |
| 44 | + htmlContent = htmlBody |
| 45 | + }; |
| 46 | + |
| 47 | + var json = JsonSerializer.Serialize(payload); |
| 48 | + var content = new StringContent(json, Encoding.UTF8, "application/json"); |
| 49 | + |
| 50 | + var client = _httpClientFactory.CreateClient("brevo"); |
| 51 | + client.DefaultRequestHeaders.Clear(); |
| 52 | + client.DefaultRequestHeaders.Add("api-key", apiKey); |
| 53 | + client.DefaultRequestHeaders.Add("accept", "application/json"); |
| 54 | + |
| 55 | + var response = await client.PostAsync("v3/smtp/email", content); |
| 56 | + var responseBody = await response.Content.ReadAsStringAsync(); |
| 57 | + |
| 58 | + if (response.IsSuccessStatusCode) |
| 59 | + { |
| 60 | + _logger.LogInformation("[Brevo] E-mail enviado para {To} — Assunto: {Subject}", toEmail, subject); |
| 61 | + } |
| 62 | + else |
| 63 | + { |
| 64 | + _logger.LogError("[Brevo] Falha ao enviar e-mail para {To}. Status: {Status}, Resposta: {Body}", toEmail, response.StatusCode, responseBody); |
| 65 | + throw new HttpRequestException($"Brevo API retornou {response.StatusCode}: {responseBody}"); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
| 69 | + |
0 commit comments