@@ -0,0 +1,46 @@
|
||||
using Api.Services.Contracts;
|
||||
using Api.Settings;
|
||||
using MailKit.Net.Smtp;
|
||||
using MailKit.Security;
|
||||
using Microsoft.Extensions.Options;
|
||||
using MimeKit;
|
||||
|
||||
namespace Api.Services;
|
||||
|
||||
public sealed class EmailService : IEmailService
|
||||
{
|
||||
private readonly SmtpSettings _settings;
|
||||
private readonly ILogger<EmailService> _logger;
|
||||
|
||||
public EmailService(IOptions<SmtpSettings> options, ILogger<EmailService> logger)
|
||||
{
|
||||
_settings = options.Value;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task SendMatchAsync(string? explicitTo, string subject, string body, CancellationToken ct)
|
||||
{
|
||||
var to = !string.IsNullOrWhiteSpace(explicitTo) ? explicitTo : _settings.ToEmail;
|
||||
if (string.IsNullOrWhiteSpace(_settings.Host) || string.IsNullOrWhiteSpace(to))
|
||||
{
|
||||
_logger.LogInformation("SMTP is not configured. Skipping CV matcher email.");
|
||||
return;
|
||||
}
|
||||
|
||||
var message = new MimeMessage();
|
||||
message.From.Add(MailboxAddress.Parse(_settings.FromEmail));
|
||||
message.To.Add(MailboxAddress.Parse(to));
|
||||
message.Subject = subject;
|
||||
message.Body = new TextPart("plain") { Text = body };
|
||||
|
||||
using var client = new SmtpClient();
|
||||
var secureSocket = _settings.UseStartTls ? SecureSocketOptions.StartTls : SecureSocketOptions.Auto;
|
||||
await client.ConnectAsync(_settings.Host, _settings.Port, secureSocket, ct);
|
||||
if (!string.IsNullOrWhiteSpace(_settings.Username))
|
||||
{
|
||||
await client.AuthenticateAsync(_settings.Username, _settings.Password, ct);
|
||||
}
|
||||
await client.SendAsync(message, ct);
|
||||
await client.DisconnectAsync(true, ct);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user