Add SMTP email delivery and deployment config
This commit is contained in:
1 parent
28fc49ea39
commit
c96eb155ae
12 files changed
+160
-28
No files matched your search
@@ -8,12 +8,15 @@ using Helpdesk.Infrastructure.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using MimeKit;
|
||||
|
||||
namespace Helpdesk.Infrastructure;
|
||||
|
||||
public static class DependencyInjection
|
||||
{
|
||||
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
|
||||
public static IServiceCollection AddInfrastructure(
|
||||
this IServiceCollection services, IConfiguration configuration, IHostEnvironment environment)
|
||||
{
|
||||
var connectionString = configuration.GetConnectionString("Helpdesk")
|
||||
?? throw new InvalidOperationException("Chybí připojovací řetězec ConnectionStrings:Helpdesk.");
|
||||
@@ -33,7 +36,7 @@ public static class DependencyInjection
|
||||
services.AddSingleton<IPasswordHasher, BCryptPasswordHasher>();
|
||||
services.AddSingleton<ITokenService, JwtTokenService>();
|
||||
services.AddSingleton<IRevokedTokenStore, RevokedTokenStore>();
|
||||
services.AddSingleton<IEmailSender, LoggingEmailSender>();
|
||||
AddEmailSender(services, configuration.GetSection("Smtp"), environment);
|
||||
services.AddSingleton<IAttachmentStore, FileAttachmentStore>();
|
||||
|
||||
services.AddHostedService<RevokedTokenStoreLoader>();
|
||||
@@ -41,4 +44,25 @@ public static class DependencyInjection
|
||||
services.AddHostedService<AuthTokenCleanupService>();
|
||||
return services;
|
||||
}
|
||||
|
||||
private static void AddEmailSender(IServiceCollection services, IConfigurationSection configuration, IHostEnvironment environment)
|
||||
{
|
||||
if (environment.IsDevelopment() && string.IsNullOrWhiteSpace(configuration["Mailbox"]) &&
|
||||
string.IsNullOrWhiteSpace(configuration["Password"]))
|
||||
{
|
||||
services.AddSingleton<IEmailSender, LoggingEmailSender>();
|
||||
return;
|
||||
}
|
||||
|
||||
services.AddOptions<SmtpOptions>()
|
||||
.Bind(configuration)
|
||||
.Validate(options => !string.IsNullOrWhiteSpace(options.Host) && options.Port is >= 1 and <= 65535,
|
||||
"Nastavte platný SMTP server a port.")
|
||||
.Validate(options => MailboxAddress.TryParse(options.Mailbox, out var mailbox) &&
|
||||
mailbox.Address == options.Mailbox && mailbox.Address.Contains('@'),
|
||||
"Nastavte celou e-mailovou adresu SMTP schránky.")
|
||||
.Validate(options => !string.IsNullOrWhiteSpace(options.Password), "Nastavte heslo SMTP schránky.")
|
||||
.ValidateOnStart();
|
||||
services.AddSingleton<IEmailSender, SmtpEmailSender>();
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,19 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Email;
|
||||
|
||||
/// <summary>
|
||||
/// Vývojová náhrada odesílání e-mailů – obsah zapíše do logu (odkaz pro ověření e-mailu je tak vidět
|
||||
/// v <c>docker compose logs api</c>). Odesílání přes SMTP (MailKit + Mailpit) přijde s notifikacemi.
|
||||
/// Vývojová náhrada odesílání e-mailů, pokud schránka SMTP není nakonfigurována.
|
||||
/// </summary>
|
||||
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger, IHostEnvironment environment) : IEmailSender
|
||||
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger) : IEmailSender
|
||||
{
|
||||
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (environment.IsDevelopment())
|
||||
LogEmail(to, subject, body);
|
||||
else
|
||||
LogMissingTransport();
|
||||
LogEmail(to, subject, body);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{Body}")]
|
||||
private partial void LogEmail(string to, string subject, string body);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "E-mail nebyl odeslán. Pro toto prostředí není nakonfigurován poštovní transport.")]
|
||||
private partial void LogMissingTransport();
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System.Net.Sockets;
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Application.Common;
|
||||
using MailKit;
|
||||
using MailKit.Net.Smtp;
|
||||
using MailKit.Security;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using MimeKit;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Email;
|
||||
|
||||
internal sealed class SmtpOptions
|
||||
{
|
||||
public string Host { get; set; } = "smtp.seznam.cz";
|
||||
public int Port { get; set; } = 465;
|
||||
public string Mailbox { get; set; } = "";
|
||||
public string Password { get; set; } = "";
|
||||
}
|
||||
|
||||
internal sealed partial class SmtpEmailSender(IOptions<SmtpOptions> options, ILogger<SmtpEmailSender> logger) : IEmailSender
|
||||
{
|
||||
public async Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!MailboxAddress.TryParse(to, out var recipient))
|
||||
{
|
||||
LogDeliveryFailure("InvalidRecipient");
|
||||
throw new EmailDeliveryException();
|
||||
}
|
||||
|
||||
var settings = options.Value;
|
||||
using var message = new MimeMessage { Subject = subject, Body = new TextPart("plain") { Text = body } };
|
||||
message.From.Add(MailboxAddress.Parse(settings.Mailbox));
|
||||
message.To.Add(recipient);
|
||||
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
using var client = new SmtpClient();
|
||||
try
|
||||
{
|
||||
await client.ConnectAsync(settings.Host, settings.Port, SecureSocketOptions.SslOnConnect, timeout.Token);
|
||||
await client.AuthenticateAsync(settings.Mailbox, settings.Password, timeout.Token);
|
||||
await client.SendAsync(message, timeout.Token);
|
||||
}
|
||||
catch (Exception exception) when (!cancellationToken.IsCancellationRequested &&
|
||||
exception is (IOException or SocketException or CommandException or ProtocolException or
|
||||
AuthenticationException or SslHandshakeException or NotSupportedException or TimeoutException or
|
||||
OperationCanceledException))
|
||||
{
|
||||
LogDeliveryFailure(exception.GetType().Name);
|
||||
throw new EmailDeliveryException();
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Doručení e-mailu přes SMTP selhalo ({FailureType}).")]
|
||||
private partial void LogDeliveryFailure(string failureType);
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
<PackageReference Include="MySqlConnector" />
|
||||
<PackageReference Include="EFCore.NamingConventions" />
|
||||
<PackageReference Include="BCrypt.Net-Next" />
|
||||
<PackageReference Include="MailKit" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
||||
|
||||
Reference in new issue
Block a user