feat: add email-api service and email-api-models contract project
New internal service that centralises SMTP email sending. - email-api-models: SendEmailRequest DTO, IEmailApiClient Refit interface, EmailApiSettings - email-api: SmtpEmailDispatcher (MailKit), EmailController (POST /api/email/send), branded HTML shell wrapper, shared-Files-volume attachment support - Protected by X-Internal-Api-Key via UseInternalApiKeyProtection() - No exposed Docker port — internal network only (http://email-api:8080) Closes #22 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace EmailApi.Models.Requests;
|
||||
|
||||
public sealed class SendEmailRequest
|
||||
{
|
||||
public required List<string> 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; }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace EmailApi.Models.Settings;
|
||||
|
||||
public sealed class EmailApiSettings
|
||||
{
|
||||
public string BaseUrl { get; set; } = "";
|
||||
public string InternalApiKey { get; set; } = "";
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<AssemblyName>email-api-models</AssemblyName>
|
||||
<RootNamespace>EmailApi.Models</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Refit.HttpClientFactory" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -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 |
|
||||
@@ -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<IActionResult> Send([FromBody] SendEmailRequest request, CancellationToken ct)
|
||||
{
|
||||
await _dispatcher.SendAsync(request, ct);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
@@ -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"]
|
||||
@@ -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<SmtpSettings>(builder.Configuration.GetSection("Smtp"));
|
||||
builder.Services.Configure<FileStorageSettings>(builder.Configuration.GetSection("FileStorage"));
|
||||
|
||||
builder.Services.AddScoped<SmtpEmailDispatcher>();
|
||||
|
||||
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();
|
||||
}
|
||||
@@ -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<SmtpEmailDispatcher> _log;
|
||||
private readonly string _environmentName;
|
||||
|
||||
private static readonly string HtmlShellStart = """
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
|
||||
<body style="margin:0;padding:0;background:#f4f4f4;font-family:Arial,Helvetica,sans-serif">
|
||||
<table width="100%" cellpadding="0" cellspacing="0" style="padding:20px 0">
|
||||
<tr><td align="center">
|
||||
<table width="600" cellpadding="0" cellspacing="0"
|
||||
style="background:#ffffff;border-radius:8px;max-width:600px">
|
||||
<tr><td style="background:#2c5282;padding:24px 32px;border-radius:8px 8px 0 0">
|
||||
<h1 style="margin:0;color:#ffffff;font-size:22px;font-weight:600">myAi</h1>
|
||||
</td></tr>
|
||||
<tr><td style="padding:32px">
|
||||
""";
|
||||
|
||||
private static readonly string HtmlShellEnd = """
|
||||
</td></tr>
|
||||
<tr><td style="background:#f8f9fa;padding:16px 32px;text-align:center;
|
||||
color:#6c757d;font-size:12px;border-radius:0 0 8px 8px">
|
||||
Automated message from myAi.
|
||||
</td></tr>
|
||||
</table>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
""";
|
||||
|
||||
public SmtpEmailDispatcher(
|
||||
IOptions<SmtpSettings> smtp,
|
||||
IOptions<FileStorageSettings> fileStorage,
|
||||
ILogger<SmtpEmailDispatcher> 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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
<RootNamespace>EmailApi</RootNamespace>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<NoWarn>$(NoWarn);1591</NoWarn>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MailKit" />
|
||||
<PackageReference Include="Serilog.AspNetCore" />
|
||||
<PackageReference Include="Serilog.Enrichers.Environment" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" />
|
||||
<PackageReference Include="Serilog.Sinks.Email" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Helpers\common-helpers\common-helpers.csproj" />
|
||||
<ProjectReference Include="..\..\Helpers\startup-helpers\startup-helpers.csproj" />
|
||||
<ProjectReference Include="..\api-models\api-models.csproj" />
|
||||
<ProjectReference Include="..\common\common.csproj" />
|
||||
<ProjectReference Include="..\email-api-models\email-api-models.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
Reference in New Issue
Block a user