84 lines
3.0 KiB
C#

using Marco.Pms.Model.Utilities;
using Microsoft.Extensions.Options;
using MailKit.Net.Smtp;
using MimeKit;
namespace MarcoBMS.Services.Service
{
public class EmailSender : IEmailSender
{
private readonly SmtpSettings _smtpSettings;
private readonly IConfiguration _configuration;
public EmailSender(IOptions<SmtpSettings> emailSettings, IConfiguration configuration)
{
_smtpSettings = emailSettings.Value;
_configuration = configuration;
}
public async Task<string> GetEmailTemplate(string templateName, Dictionary<string, string> replacements)
{
string path = Path.Combine(Directory.GetCurrentDirectory(), "EmailTemplates", $"{templateName}.html");
if (!File.Exists(path))
throw new FileNotFoundException("Template file not found");
string content = await File.ReadAllTextAsync(path);
foreach (var item in replacements)
{
content = content.Replace($"{{{{{item.Key}}}}}", item.Value);
}
return content;
}
public async Task SendResetPasswordEmailOnRegister(string toEmail, string toName, string resetLink)
{
var replacements = new Dictionary<string, string>
{
{ "MAIL_TITLE", "New registration,Reset Your Password" },
{ "RESET_PWD_URL", resetLink },
{ "RECEIVER_NAME", toName }
};
string emailBody = await GetEmailTemplate("new-user-email", replacements);
await SendEmailAsync(toEmail, "New user registration, Reset Your Password", emailBody);
}
public async Task SendResetPasswordEmail(string toEmail, string userName, string resetLink)
{
var replacements = new Dictionary<string, string>
{
{ "MAIL_TITLE", "Reset Your Password" },
{ "RESET_PWD_URL", resetLink }
};
string emailBody = await GetEmailTemplate("forgot-password", replacements);
await SendEmailAsync(toEmail, "Reset Your Password", emailBody);
}
public async Task SendEmailAsync(string toEmail, string subject, string body)
{
var email = new MimeMessage();
email.From.Add(new MailboxAddress(_smtpSettings.SenderName, _smtpSettings.SenderEmail));
email.To.Add(MailboxAddress.Parse(toEmail));
email.Subject = subject;
var bodyBuilder = new BodyBuilder { HtmlBody = body };
email.Body = bodyBuilder.ToMessageBody();
using var smtp = new SmtpClient();
await smtp.ConnectAsync(_smtpSettings.SmtpServer, _smtpSettings.Port, MailKit.Security.SecureSocketOptions.StartTls);
await smtp.AuthenticateAsync(_smtpSettings.SenderEmail, _smtpSettings.Password);
await smtp.SendAsync(email);
await smtp.DisconnectAsync(true);
}
}
}