// Copyright (c) 2023 Tudor Stanciu using Correo.Abstractions; using Correo.Abstractions.Extensions; using Correo.SendGrid.Extensions; using Correo.SendGrid.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using SendGrid; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Correo.SendGrid { internal class SendGridService : IMailer { private readonly IOptions _optionsAccessor; private readonly SendGridClient _client; private readonly ILogger _logger; public SendGridService(IOptions optionsAccessor, ILogger logger) { _optionsAccessor = optionsAccessor; _logger = logger; _client = new SendGridClient(_optionsAccessor.Value.ApiKey); } public void SendEmail(EmailMessage message) { SendEmailAsync(message).GetAwaiter().GetResult(); } public async Task SendEmailAsync(EmailMessage message, CancellationToken token = default) { var mailMessage = message.ToSendGridMessage(); var response = await _client.SendEmailAsync(mailMessage, token); if (response.IsSuccessStatusCode) _logger.LogInformation(message.Log()); else { var body = await response.DeserializeResponseBodyAsync(); var found = body.TryGetValue("errors", out var jsonData); if (found) { string errorsString = Convert.ToString(jsonData); var errors = JsonConvert.DeserializeObject(errorsString); var errorMessage = string.Join("; ", errors.Select(z => z.Message)); throw new Exception(errorMessage); } throw new Exception(response.StatusCode.ToString()); } } } }