feat: add test button to create channel form using ad-hoc smtp test endpoint
- Add TestSmtpCommand and TestSmtpHandler for ad-hoc smtp testing without saving - Add POST /admin/channels/test-smtp endpoint accepting raw smtp settings - Show Test button on both Create and Edit forms - Test reads current form values so channel can be tested before saving
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
using HrynCo.NotificationService.Services.Core;
|
||||
using MediatR;
|
||||
|
||||
namespace HrynCo.NotificationService.Services.EmailChannels.TestSmtp;
|
||||
|
||||
/// <summary>
|
||||
/// Sends a test email using the provided SMTP settings without persisting anything.
|
||||
/// </summary>
|
||||
public sealed record TestSmtpCommand(
|
||||
string Host,
|
||||
int Port,
|
||||
string Username,
|
||||
string Password,
|
||||
bool UseSsl,
|
||||
string FromEmail,
|
||||
string FromName,
|
||||
string ToEmail
|
||||
) : IRequest<ServiceResult<Core.Unit>>;
|
||||
@@ -0,0 +1,52 @@
|
||||
using System.Net;
|
||||
using System.Net.Mail;
|
||||
using HrynCo.NotificationService.DAL.Abstract;
|
||||
using HrynCo.NotificationService.Services.Core;
|
||||
using HrynCo.NotificationService.Services.Logging;
|
||||
using static HrynCo.NotificationService.Services.Core.ServiceResultHelper;
|
||||
|
||||
namespace HrynCo.NotificationService.Services.EmailChannels.TestSmtp;
|
||||
|
||||
internal sealed class TestSmtpHandler
|
||||
: RequestHandler<TestSmtpCommand, ServiceResult<Unit>>
|
||||
{
|
||||
public TestSmtpHandler(
|
||||
IContextualSerilogLogger<TestSmtpCommand> logger,
|
||||
IUnitOfWork unitOfWork)
|
||||
: base(logger, unitOfWork)
|
||||
{
|
||||
}
|
||||
|
||||
protected override async Task<ServiceResult<Unit>> DoOnHandle(
|
||||
TestSmtpCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var client = new SmtpClient(request.Host, request.Port)
|
||||
{
|
||||
EnableSsl = request.UseSsl,
|
||||
Credentials = string.IsNullOrWhiteSpace(request.Username)
|
||||
? null
|
||||
: new NetworkCredential(request.Username, request.Password)
|
||||
};
|
||||
|
||||
using var mail = new MailMessage
|
||||
{
|
||||
From = new MailAddress(request.FromEmail, request.FromName),
|
||||
Subject = "✅ Test email from Notification Service",
|
||||
Body = "<p>This is a test email sent from the <b>Notification Service</b> admin panel to verify the channel settings.</p>",
|
||||
IsBodyHtml = true
|
||||
};
|
||||
mail.To.Add(new MailAddress(request.ToEmail));
|
||||
|
||||
await client.SendMailAsync(mail, cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Error(ex, "Ad-hoc SMTP test failed for host {Host}", request.Host);
|
||||
return Failure<Unit>(ex.Message);
|
||||
}
|
||||
|
||||
return Success(Unit.Value);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user