Files
Swarm/DysonNetwork.Shared/Services/EmailService.cs
2025-07-08 23:55:31 +08:00

78 lines
2.3 KiB
C#

using MailKit.Net.Smtp;
using MimeKit;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace DysonNetwork.Shared.Services;
public class EmailService
{
private readonly IConfiguration _configuration;
private readonly ILogger<EmailService> _logger;
public EmailService(IConfiguration configuration, ILogger<EmailService> logger)
{
_configuration = configuration;
_logger = logger;
}
public async Task SendEmailAsync(
string toName,
string toEmail,
string subject,
string body,
Dictionary<string, string>? headers = null
)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(
_configuration["Email:SenderName"],
_configuration["Email:SenderEmail"]
));
message.To.Add(new MailboxAddress(toName, toEmail));
message.Subject = subject;
var bodyBuilder = new BodyBuilder { HtmlBody = body };
message.Body = bodyBuilder.ToMessageBody();
if (headers != null)
{
foreach (var header in headers)
{
message.Headers.Add(header.Key, header.Value);
}
}
using var client = new SmtpClient();
try
{
await client.ConnectAsync(
_configuration["Email:SmtpHost"],
int.Parse(_configuration["Email:SmtpPort"]),
MailKit.Security.SecureSocketOptions.StartTls
);
await client.AuthenticateAsync(
_configuration["Email:SmtpUser"],
_configuration["Email:SmtpPass"]
);
await client.SendAsync(message);
_logger.LogInformation("Email sent to {ToEmail}", toEmail);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send email to {ToEmail}", toEmail);
throw;
}
finally
{
await client.DisconnectAsync(true);
}
}
public async Task SendTemplatedEmailAsync<T>(string toName, string toEmail, string subject, string htmlBody)
{
await SendEmailAsync(toName, toEmail, subject, htmlBody);
}
}