48 lines
1.7 KiB
C#
48 lines
1.7 KiB
C#
using dy.net.model.entity;
|
|
using MailKit.Net.Smtp;
|
|
using MimeKit;
|
|
|
|
namespace dy.net.service
|
|
{
|
|
public interface IEmailNotificationSender
|
|
{
|
|
Task SendAsync(
|
|
EmailNotificationSettings settings,
|
|
string password,
|
|
string subject,
|
|
string htmlBody,
|
|
CancellationToken cancellationToken = default);
|
|
}
|
|
|
|
public sealed class EmailNotificationSender : IEmailNotificationSender
|
|
{
|
|
public async Task SendAsync(
|
|
EmailNotificationSettings settings,
|
|
string password,
|
|
string subject,
|
|
string htmlBody,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
var message = new MimeMessage();
|
|
message.From.Add(new MailboxAddress(
|
|
string.IsNullOrWhiteSpace(settings.FromName) ? "dysync.net" : settings.FromName,
|
|
settings.FromAddress));
|
|
message.To.AddRange(EmailNotificationSettingsService.ParseRecipients(settings.Recipients));
|
|
message.Subject = subject;
|
|
message.Body = new BodyBuilder { HtmlBody = htmlBody }.ToMessageBody();
|
|
|
|
using var client = new SmtpClient();
|
|
client.Timeout = 30_000;
|
|
await client.ConnectAsync(
|
|
settings.Host,
|
|
settings.Port,
|
|
EmailNotificationSettingsService.ToSocketOptions(settings.SecurityMode),
|
|
cancellationToken);
|
|
if (!string.IsNullOrWhiteSpace(settings.UserName))
|
|
await client.AuthenticateAsync(settings.UserName, password ?? string.Empty, cancellationToken);
|
|
await client.SendAsync(message, cancellationToken);
|
|
await client.DisconnectAsync(true, cancellationToken);
|
|
}
|
|
}
|
|
}
|