|
| 1 | +using MailKit.Net.Smtp; |
| 2 | +using MailKit.Security; |
| 3 | +using Microsoft.Extensions.Hosting; |
| 4 | +using Microsoft.Extensions.Logging; |
| 5 | +using Microsoft.Extensions.Options; |
| 6 | +using Models.Options; |
| 7 | +using System; |
| 8 | +using System.Threading; |
| 9 | +using System.Threading.Tasks; |
| 10 | + |
| 11 | +namespace EmailService.Services.Initialization |
| 12 | +{ |
| 13 | + public class SmtpOptionsValidator : IHostedService |
| 14 | + { |
| 15 | + private readonly IOptions<EmailServiceOptions> emailSenderOptions; |
| 16 | + private readonly ILogger<SmtpOptionsValidator> logger; |
| 17 | + |
| 18 | + public SmtpOptionsValidator( |
| 19 | + IOptions<EmailServiceOptions> emailSenderOptions, |
| 20 | + ILogger<SmtpOptionsValidator> logger) |
| 21 | + { |
| 22 | + this.emailSenderOptions = emailSenderOptions; |
| 23 | + this.logger = logger; |
| 24 | + } |
| 25 | + public async Task StartAsync(CancellationToken cancellationToken) |
| 26 | + { |
| 27 | + logger.LogInformation("Checking smtp parameters to {Host} as {Email}", emailSenderOptions.Value.SmtpHost, emailSenderOptions.Value.Email); |
| 28 | + |
| 29 | + using var client = new SmtpClient(); |
| 30 | + try |
| 31 | + { |
| 32 | + await client.ConnectAsync(emailSenderOptions.Value.SmtpHost, emailSenderOptions.Value.SmtpPort, SecureSocketOptions.Auto, cancellationToken); |
| 33 | + await client.AuthenticateAsync(emailSenderOptions.Value.Email, emailSenderOptions.Value.Password, cancellationToken); |
| 34 | + await client.DisconnectAsync(true, cancellationToken); |
| 35 | + logger.LogInformation("SMTP optinos validated successfully"); |
| 36 | + } |
| 37 | + catch (Exception ex) |
| 38 | + { |
| 39 | + logger.LogCritical(ex, "Can't connect to STMP host"); |
| 40 | + throw; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + public Task StopAsync(CancellationToken cancellationToken) |
| 45 | + { |
| 46 | + return Task.CompletedTask; |
| 47 | + } |
| 48 | + } |
| 49 | +} |
0 commit comments