classlib/ExpenseTracker.Infrastructure/Email/EmailSenderService.cs
2024-08-07 21:12:02 +03:00

64 lines
2.0 KiB
C#

using System.Text;
using ExpenseTracker.Application.Common.Interfaces.Services;
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Configuration;
using MimeKit;
namespace ExpenseTracker.Infrastructure.Email;
public class EmailSenderService : IEmailSenderService
{
private readonly IConfiguration _configuration;
public EmailSenderService(IConfiguration configuration)
{
_configuration = configuration;
}
public async Task SendAsync(
ICollection<string> recipientAddresses,
string subject,
string message,
CancellationToken cancellationToken)
{
var smtpClientHost = _configuration.GetSection("Email").GetValue<string>("Host");
var smtpClientPort = _configuration.GetSection("Email").GetValue<int>("Port");
var smtpClientUsername = _configuration.GetSection("Email").GetValue<string>("Username");
var smtpClientPassword = _configuration.GetSection("Email").GetValue<string>("Password");
var fromAddres = _configuration.GetSection("Email").GetValue<string>("SenderAddress");;
var fromName = _configuration.GetSection("Email").GetValue<string>("SenderName");;
var subj = subject;
var body = message;
var msg = new MimeMessage();
msg.From.Add(new MailboxAddress(fromName, fromAddres));
foreach (var address in recipientAddresses)
{
msg.To.Add(new MailboxAddress("", address));
}
msg.Subject = subj;
msg.Body = new TextPart("plain")
{
Text = body
};
using (var client = new SmtpClient())
{
await client.ConnectAsync(smtpClientHost, smtpClientPort, SecureSocketOptions.SslOnConnect, cancellationToken);
await client.AuthenticateAsync(smtpClientUsername, smtpClientPassword, cancellationToken);
await client.SendAsync(msg, cancellationToken);
await client.DisconnectAsync(true, cancellationToken);
}
}
}