diff --git a/Apis/email-api-models/Clients/IEmailApiClient.cs b/Apis/email-api-models/Clients/IEmailApiClient.cs new file mode 100644 index 0000000..73aa438 --- /dev/null +++ b/Apis/email-api-models/Clients/IEmailApiClient.cs @@ -0,0 +1,10 @@ +using EmailApi.Models.Requests; +using Refit; + +namespace EmailApi.Models.Clients; + +public interface IEmailApiClient +{ + [Post("/api/email/send")] + Task SendAsync(SendEmailRequest request, CancellationToken ct = default); +} diff --git a/Apis/email-api-models/Requests/SendEmailRequest.cs b/Apis/email-api-models/Requests/SendEmailRequest.cs new file mode 100644 index 0000000..5d2f021 --- /dev/null +++ b/Apis/email-api-models/Requests/SendEmailRequest.cs @@ -0,0 +1,10 @@ +namespace EmailApi.Models.Requests; + +public sealed class SendEmailRequest +{ + public required List To { get; init; } + public string? ReplyTo { get; init; } + public required string Subject { get; init; } + public required string HtmlBody { get; init; } + public string? AttachmentPath { get; init; } +} diff --git a/Apis/email-api-models/Settings/EmailApiSettings.cs b/Apis/email-api-models/Settings/EmailApiSettings.cs new file mode 100644 index 0000000..1a27d41 --- /dev/null +++ b/Apis/email-api-models/Settings/EmailApiSettings.cs @@ -0,0 +1,7 @@ +namespace EmailApi.Models.Settings; + +public sealed class EmailApiSettings +{ + public string BaseUrl { get; set; } = ""; + public string InternalApiKey { get; set; } = ""; +} diff --git a/Apis/email-api-models/email-api-models.csproj b/Apis/email-api-models/email-api-models.csproj new file mode 100644 index 0000000..45aaa9d --- /dev/null +++ b/Apis/email-api-models/email-api-models.csproj @@ -0,0 +1,12 @@ + + + net10.0 + enable + enable + email-api-models + EmailApi.Models + + + + + diff --git a/Apis/email-api/CLAUDE.md b/Apis/email-api/CLAUDE.md new file mode 100644 index 0000000..0ea58d0 --- /dev/null +++ b/Apis/email-api/CLAUDE.md @@ -0,0 +1,40 @@ +# email-api — Internal Email Sending Service + +Internal only. Reachable at `http://email-api:8080` within `myai-network`. Not exposed to the internet. + +## Responsibilities + +- Accepts `POST /api/email/send` requests from internal services (`api`, `cv-search-job`) +- Wraps the provided HTML body fragment in a branded HTML shell (blue header, white card, grey footer) +- Sends the email via SMTP using MailKit +- Attaches files from the shared `Files` volume when `AttachmentPath` is provided +- Protected by `X-Internal-Api-Key` via `UseInternalApiKeyProtection()` + +## Key route + +| Method | Route | Description | +|--------|-------|-------------| +| POST | `/api/email/send` | Send an HTML email. Returns 204 No Content. | + +## Request body (`SendEmailRequest`) + +| Field | Required | Notes | +|-------|----------|-------| +| `To` | ✅ | List of recipient addresses | +| `ReplyTo` | ❌ | Optional reply-to address | +| `Subject` | ✅ | Plain text (service prepends `[ENV_NAME]`) | +| `HtmlBody` | ✅ | HTML fragment — wrapped in branded shell by this service | +| `AttachmentPath` | ❌ | Path relative to `FileStorage:Path`, e.g. `"{cvDocumentId}.pdf"` | + +## Consumers + +- `api` — via `IEmailApiClient` Refit interface (contact, subscribe, file-download, match emails) +- `cv-search-job` — via `IEmailApiClient` Refit interface (job search results email) + +## Settings + +| Section | Env var | Notes | +|---------|---------|-------| +| `Smtp` | `Smtp__Host`, `Smtp__Username`, `Smtp__Password`, etc. | SMTP server config — only configured here, not in consumers | +| `FileStorage` | `FileStorage__Path` | Must match the shared `Files` volume mount path | +| `InternalApi` | `EmailApi__InternalApiKey` | API key enforced on every request | diff --git a/Apis/email-api/Controllers/EmailController.cs b/Apis/email-api/Controllers/EmailController.cs new file mode 100644 index 0000000..e7e628f --- /dev/null +++ b/Apis/email-api/Controllers/EmailController.cs @@ -0,0 +1,24 @@ +using EmailApi.Models.Requests; +using EmailApi.Services; +using Microsoft.AspNetCore.Mvc; +using Swashbuckle.AspNetCore.Annotations; + +namespace EmailApi.Controllers; + +[ApiController] +[Route("api/email")] +public sealed class EmailController : ControllerBase +{ + private readonly SmtpEmailDispatcher _dispatcher; + + public EmailController(SmtpEmailDispatcher dispatcher) => _dispatcher = dispatcher; + + [HttpPost("send")] + [SwaggerOperation(Summary = "Send an HTML email via SMTP")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task Send([FromBody] SendEmailRequest request, CancellationToken ct) + { + await _dispatcher.SendAsync(request, ct); + return NoContent(); + } +} diff --git a/Apis/email-api/Dockerfile b/Apis/email-api/Dockerfile new file mode 100644 index 0000000..691ff27 --- /dev/null +++ b/Apis/email-api/Dockerfile @@ -0,0 +1,31 @@ +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build +ARG BUILD_CONFIGURATION=Release +WORKDIR /src + +COPY Apis/email-api/email-api.csproj Apis/email-api/ +COPY Apis/email-api-models/email-api-models.csproj Apis/email-api-models/ +COPY Apis/api-models/api-models.csproj Apis/api-models/ +COPY Apis/common/common.csproj Apis/common/ +COPY Helpers/common-helpers/common-helpers.csproj Helpers/common-helpers/ +COPY Helpers/startup-helpers/startup-helpers.csproj Helpers/startup-helpers/ +COPY Directory.Packages.props ./ + +RUN dotnet restore Apis/email-api/email-api.csproj + +COPY Apis/email-api/ Apis/email-api/ +COPY Apis/email-api-models/ Apis/email-api-models/ +COPY Apis/api-models/ Apis/api-models/ +COPY Apis/common/ Apis/common/ +COPY Helpers/common-helpers/ Helpers/common-helpers/ +COPY Helpers/startup-helpers/ Helpers/startup-helpers/ + +RUN dotnet publish Apis/email-api/email-api.csproj -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false + +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final +WORKDIR /app +EXPOSE 8080 +ENV ASPNETCORE_URLS=http://0.0.0.0:8080 + +COPY --from=build /app/publish . + +ENTRYPOINT ["dotnet", "email-api.dll"] diff --git a/Apis/email-api/Program.cs b/Apis/email-api/Program.cs new file mode 100644 index 0000000..e174e42 --- /dev/null +++ b/Apis/email-api/Program.cs @@ -0,0 +1,54 @@ +using System.Reflection; +using EmailApi.Services; +using Models.Settings; +using Serilog; +using StartupHelpers; + +StartupExtensions.LoadDotEnvFile(); + +const string ServiceName = "email-api"; +var appVersion = StartupExtensions.GetApplicationVersion(Assembly.GetExecutingAssembly()); + +try +{ + var builder = WebApplication.CreateBuilder(args); + + builder.ConfigureJsonSerilog(ServiceName, appVersion); + Log.Information("Starting {Service} version {AppVersion}", ServiceName, appVersion); + + builder.AddAzureKeyVaultIfConfigured(); + + builder.Services.AddControllers(); + builder.Services.AddSwaggerWithXmlComments(Assembly.GetExecutingAssembly(), "Email API"); + + builder.Services.Configure(builder.Configuration.GetSection("Smtp")); + builder.Services.Configure(builder.Configuration.GetSection("FileStorage")); + + builder.Services.AddScoped(); + + var app = builder.Build(); + + app.LogStartupDiagnostics(ServiceName); + + app.UseDefaultSerilogRequestLogging(); + app.UseJsonExceptionHandler(ServiceName); + app.UseSwaggerInDevelopment("Email API", "EmailAPI"); + + app.UseInternalApiKeyProtection(); + + app.UseRouting(); + app.UseAuthorization(); + app.MapControllers(); + + Log.Information("{Service} startup complete. Listening for requests...", ServiceName); + app.Run(); +} +catch (Exception ex) +{ + Log.Fatal(ex, "{Service} terminated unexpectedly", ServiceName); +} +finally +{ + Log.Information("Shutting down {Service}", ServiceName); + Log.CloseAndFlush(); +} diff --git a/Apis/email-api/Services/SmtpEmailDispatcher.cs b/Apis/email-api/Services/SmtpEmailDispatcher.cs new file mode 100644 index 0000000..3ca3eb0 --- /dev/null +++ b/Apis/email-api/Services/SmtpEmailDispatcher.cs @@ -0,0 +1,111 @@ +using EmailApi.Models.Requests; +using MailKit.Net.Smtp; +using MailKit.Security; +using Microsoft.Extensions.Options; +using MimeKit; +using Models.Settings; + +namespace EmailApi.Services; + +public sealed class SmtpEmailDispatcher +{ + private readonly SmtpSettings _smtp; + private readonly FileStorageSettings _fileStorage; + private readonly ILogger _log; + private readonly string _environmentName; + + private static readonly string HtmlShellStart = """ + + + + + + +
+ + + + +
+

myAi

+
+ """; + + private static readonly string HtmlShellEnd = """ +
+ Automated message from myAi. +
+
+ + + """; + + public SmtpEmailDispatcher( + IOptions smtp, + IOptions fileStorage, + ILogger log) + { + _smtp = smtp.Value; + _fileStorage = fileStorage.Value; + _log = log; + _environmentName = Environment.GetEnvironmentVariable("APP_ENVIRONMENT_NAME") ?? "Development"; + } + + public async Task SendAsync(SendEmailRequest req, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(_smtp.Host)) + { + _log.LogWarning("SMTP host not configured — email skipped (to: {To})", string.Join(", ", req.To)); + return; + } + + var msg = new MimeMessage(); + msg.From.Add(MailboxAddress.Parse(_smtp.Username)); + + foreach (var to in req.To) + msg.To.Add(MailboxAddress.Parse(to)); + + if (!string.IsNullOrWhiteSpace(req.ReplyTo)) + msg.ReplyTo.Add(MailboxAddress.Parse(req.ReplyTo)); + + msg.Subject = $"[{_environmentName}] {req.Subject}".Trim(); + + var builder = new BodyBuilder + { + HtmlBody = HtmlShellStart + req.HtmlBody + HtmlShellEnd + }; + + if (!string.IsNullOrWhiteSpace(req.AttachmentPath)) + { + var fullPath = Path.Combine(_fileStorage.Path, req.AttachmentPath); + if (File.Exists(fullPath)) + { + builder.Attachments.Add(fullPath); + _log.LogDebug("Attachment added: {Path}", fullPath); + } + else + { + _log.LogWarning("Attachment not found, skipping: {Path}", fullPath); + } + } + + msg.Body = builder.ToMessageBody(); + + _log.LogInformation("Sending email to {Recipients} subject {Subject}", + string.Join(", ", req.To), req.Subject); + + using var client = new SmtpClient(); + var tls = _smtp.UseStartTls ? SecureSocketOptions.StartTls : SecureSocketOptions.Auto; + await client.ConnectAsync(_smtp.Host, _smtp.Port, tls, ct); + + if (!string.IsNullOrWhiteSpace(_smtp.Username)) + await client.AuthenticateAsync(_smtp.Username, _smtp.Password, ct); + + await client.SendAsync(msg, ct); + await client.DisconnectAsync(true, ct); + + _log.LogInformation("Email sent successfully to {Recipients}", string.Join(", ", req.To)); + } +} diff --git a/Apis/email-api/email-api.csproj b/Apis/email-api/email-api.csproj new file mode 100644 index 0000000..111de58 --- /dev/null +++ b/Apis/email-api/email-api.csproj @@ -0,0 +1,27 @@ + + + net10.0 + enable + enable + Linux + EmailApi + true + $(NoWarn);1591 + + + + + + + + + + + + + + + + + +