using System.Net.Http.Json; using System.Text.Json; namespace SoroushAsadi.Services; public class EmailService(HttpClient http, IConfiguration config, ILogger logger) { private string? ApiKey => config["RESEND_API_KEY"] ?? Environment.GetEnvironmentVariable("RESEND_API_KEY"); private string? Inbox => config["CONTACT_INBOX"] ?? Environment.GetEnvironmentVariable("CONTACT_INBOX"); private string? From => config["CONTACT_FROM"] ?? Environment.GetEnvironmentVariable("CONTACT_FROM"); public record ContactForm( string Name, string Company, string Service, string Budget, string Message, string Locale); /// null on success, error string on failure. public async Task SendContactAsync(ContactForm form) { if (ApiKey is null || Inbox is null || From is null) { logger.LogInformation("[contact] received (no Resend key — logging only): {Name}", form.Name); return null; // dev no-op } var html = $"""

New consultation request

Name{Esc(form.Name)}
Company{Esc(form.Company)}
Service{Esc(form.Service)}
Budget{Esc(form.Budget)}
Locale{Esc(form.Locale)}

Message

{Esc(form.Message)}

"""; using var req = new HttpRequestMessage(HttpMethod.Post, "https://api.resend.com/emails"); req.Headers.Add("Authorization", $"Bearer {ApiKey}"); req.Content = JsonContent.Create(new { from = From, to = new[] { Inbox }, subject = $"New consultation request — {form.Name}", html }); try { var res = await http.SendAsync(req); if (!res.IsSuccessStatusCode) { var body = await res.Content.ReadAsStringAsync(); logger.LogError("[contact] Resend error {Status}: {Body}", res.StatusCode, body); return "Email service rejected the request."; } return null; } catch (Exception ex) { logger.LogError(ex, "[contact] Send failed"); return "Email service unreachable."; } } private static string Esc(string? s) => System.Web.HttpUtility.HtmlEncode(s ?? ""); }