Enhance MailService: refactor constructor to accept a custom SMTP client factory and add unit tests for SendEmailAsync method
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using FoodsharingSiegen.Contracts.Model;
|
||||
using MailKit.Net.Smtp;
|
||||
@@ -15,15 +16,17 @@ namespace FoodsharingSiegen.Server.Service
|
||||
{
|
||||
private readonly MailSettings _mailSettings;
|
||||
private readonly TermSettings _termSettings;
|
||||
private readonly Func<ISmtpClient> _smtpClientFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MailService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="appSettings">The configured application settings injected by DI, containing the <see cref="MailSettings"/>.</param>
|
||||
public MailService(IOptions<AppSettings> appSettings)
|
||||
public MailService(IOptions<AppSettings> appSettings, Func<ISmtpClient>? smtpClientFactory = null)
|
||||
{
|
||||
_mailSettings = appSettings.Value.Mail;
|
||||
_termSettings = appSettings.Value.Terms;
|
||||
_smtpClientFactory = smtpClientFactory ?? (() => new SmtpClient());
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -40,7 +43,7 @@ namespace FoodsharingSiegen.Server.Service
|
||||
};
|
||||
email.Body = textPart;
|
||||
|
||||
using var smtp = new SmtpClient();
|
||||
using var smtp = _smtpClientFactory();
|
||||
var secureOptions = _mailSettings.UseSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.Auto;
|
||||
|
||||
await smtp.ConnectAsync(_mailSettings.Host, _mailSettings.Port, secureOptions);
|
||||
|
||||
Reference in New Issue
Block a user