47 lines
1.6 KiB
C#
47 lines
1.6 KiB
C#
using System.Net.Http.Headers;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using Socialize.Infrastructure.Emailer.Configuration;
|
|
using Socialize.Infrastructure.Emailer.Contracts;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Socialize.Infrastructure.Emailer.Services;
|
|
|
|
public class ResendEmailSender : IEmailSender
|
|
{
|
|
private static readonly Uri EndpointUri = new("https://api.resend.com/emails");
|
|
private readonly HttpClient _httpClient;
|
|
private readonly EmailerOptions _options;
|
|
|
|
public ResendEmailSender(
|
|
IHttpClientFactory httpClientFactory,
|
|
IOptions<EmailerOptions> options)
|
|
{
|
|
_httpClient = httpClientFactory.CreateClient();
|
|
_options = options.Value;
|
|
|
|
_httpClient.DefaultRequestHeaders.Authorization =
|
|
new AuthenticationHeaderValue("Bearer", _options.ApiKey);
|
|
|
|
_httpClient.DefaultRequestHeaders.Accept.Add(
|
|
new MediaTypeWithQualityHeaderValue("application/json"));
|
|
}
|
|
|
|
public async Task SendEmailAsync(string toEmail, string subject, string htmlMessage)
|
|
{
|
|
var payload = new { from = _options.FromEmail, to = toEmail, subject, html = htmlMessage };
|
|
|
|
string json = JsonSerializer.Serialize(payload);
|
|
StringContent content = new(json, Encoding.UTF8, "application/json");
|
|
|
|
HttpResponseMessage response = await _httpClient.PostAsync(EndpointUri, content);
|
|
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
string body = await response.Content.ReadAsStringAsync();
|
|
throw new InvalidOperationException(
|
|
$"Resend email failed: {response.StatusCode} - {body}");
|
|
}
|
|
}
|
|
}
|