Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/GZCTF/Services/Mail/MailSender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public sealed class MailSender : IMailSender, IDisposable
private readonly EmailConfig? _options;
private readonly AsyncManualResetEvent _resetEvent = new();
private readonly SmtpClient? _smtpClient;
private readonly bool _useSmtpAuthentication;
private bool _disposed;

public MailSender(
Expand All @@ -28,8 +29,15 @@ public MailSender(
{
_logger = logger;
_options = options.Value;
var hasUserName = !string.IsNullOrWhiteSpace(_options.UserName);
var hasPassword = !string.IsNullOrWhiteSpace(_options.Password);
_useSmtpAuthentication = hasUserName && hasPassword;
_cancellationToken = _cancellationTokenSource.Token;

if (hasUserName != hasPassword)
_logger.SystemLog("SMTP username/password is partially configured. SMTP AUTH will be skipped.",
TaskStatus.Degraded, LogLevel.Warning);

Comment on lines +32 to +40
if (string.IsNullOrWhiteSpace(_options.SenderAddress) ||
string.IsNullOrWhiteSpace(_options.Smtp?.Host) || _options.Smtp.Port <= 0)
return;
Expand Down Expand Up @@ -164,7 +172,7 @@ private async Task MailSenderWorker()
await _smtpClient.ConnectAsync(_options!.Smtp!.Host, _options.Smtp.Port,
cancellationToken: _cancellationToken);

if (!_smtpClient.IsAuthenticated)
if (_useSmtpAuthentication && !_smtpClient.IsAuthenticated)
await _smtpClient.AuthenticateAsync(_options!.UserName, _options.Password,
_cancellationToken);

Expand Down Expand Up @@ -214,7 +222,8 @@ private bool TestSmtpClient(CancellationToken token = default)
try
{
_smtpClient.Connect(_options!.Smtp!.Host, _options.Smtp.Port, cancellationToken: token);
_smtpClient.Authenticate(_options.UserName, _options.Password, token);
if (_useSmtpAuthentication)
_smtpClient.Authenticate(_options.UserName, _options.Password, token);
_smtpClient.Disconnect(true, token);
return true;
}
Expand Down
Loading