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
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user