private async Task ConnectAsync(ISmtpClient client, EmailConfig.OutgoingConfig cfg, CancellationToken cancellationToken) { _log.LogDebug("Connecting to mail server using {@Config}", cfg); var socketOptions = client.ConfigureSecurity(cfg.UseSecureMode); await Policy .Handle <SocketException>().Or <System.IO.IOException>().Or <SslHandshakeException>() .WaitAndRetryAsync(_retryConfig.Max, _ => _retryConfig.Delay, (exc, delay, attempt, _) => _log.LogError(exc, Message.ConnError, attempt, cfg, delay)) .ExecuteAsync(token => client.ConnectAsync(cfg.ServerAddress, cfg.Port, socketOptions, token), cancellationToken); if (!string.IsNullOrWhiteSpace(cfg.Username) && !string.IsNullOrWhiteSpace(cfg.Password)) { await Policy.Handle <SocketException>() .WaitAndRetryAsync(_retryConfig.Max, _ => _retryConfig.Delay, (exc, delay, attempt, _) => _log.LogError(exc, Message.AuthError, attempt, cfg, delay)) .ExecuteAsync(token => client.AuthenticateAsync(cfg.Username, cfg.Password, token), cancellationToken); } }