Add project files.
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
using MailKit.Net.Smtp;
|
||||
using MimeKit;
|
||||
|
||||
namespace CalendarReminder.Api.Services;
|
||||
|
||||
public class EmailSettings
|
||||
{
|
||||
public string Host { get; set; } = "";
|
||||
public int Port { get; set; } = 587;
|
||||
public string Username { get; set; } = "";
|
||||
public string Password { get; set; } = "";
|
||||
public string From { get; set; } = "";
|
||||
public bool UseSsl { get; set; } = false;
|
||||
}
|
||||
|
||||
public class EmailService
|
||||
{
|
||||
private readonly EmailSettings _settings;
|
||||
private readonly ILogger<EmailService> _logger;
|
||||
|
||||
public EmailService(IConfiguration config, ILogger<EmailService> logger)
|
||||
{
|
||||
_settings = config.GetSection("Email").Get<EmailSettings>() ?? new EmailSettings();
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task SendAsync(string toEmail, string toName, string subject, string body)
|
||||
{
|
||||
try
|
||||
{
|
||||
var message = new MimeMessage();
|
||||
message.From.Add(new MailboxAddress("CalendarReminder", _settings.From));
|
||||
message.To.Add(new MailboxAddress(toName, toEmail));
|
||||
message.Subject = subject;
|
||||
message.Body = new TextPart("html") { Text = body };
|
||||
|
||||
using var client = new SmtpClient();
|
||||
await client.ConnectAsync(_settings.Host, _settings.Port, _settings.UseSsl);
|
||||
if (!string.IsNullOrEmpty(_settings.Username))
|
||||
await client.AuthenticateAsync(_settings.Username, _settings.Password);
|
||||
await client.SendAsync(message);
|
||||
await client.DisconnectAsync(true);
|
||||
|
||||
_logger.LogInformation("Email odoslaný na {Email}", toEmail);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Chyba pri odosielaní emailu na {Email}", toEmail);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user