using System.Net;
using System.Net.Mail;
namespace ConsoleApp1;
public class MailService(SmtpSettings smtpSettings)
{
///
/// Sends a plain text email to the specified recipient.
///
/// The recipient's email address.
/// The subject of the email.
/// The body of the email.
public async Task SendEmailText(string to, string subject, string body)
{
await SendEmailInternal(to, subject, body, isHtml: false);
}
///
/// Sends an HTML email to the specified recipient using a file as the body.
///
/// The recipient's email address.
/// The subject of the email.
/// The file path of the HTML file to be used as the body of the email.
/// Optional dictionary of placeholder replacements to be applied to the HTML body.
public async Task SendEmailHtmlFile(string to, string subject, string filePath,
Dictionary? replacements = null)
{
string body = await File.ReadAllTextAsync(filePath);
if (replacements != null)
{
foreach (var replacement in replacements)
{
body = body.Replace($"{{{replacement.Key}}}", replacement.Value);
}
}
await SendEmailInternal(to, subject, body, isHtml: true);
}
///
/// Sends an email to the specified recipient.
///
/// The recipient's email address.
/// The subject of the email.
/// The body of the email.
/// Indicates whether the body of the email is HTML.
private async Task SendEmailInternal(string to, string subject, string body, bool isHtml)
{
using var client = new SmtpClient(smtpSettings.SmtpServer, smtpSettings.SmtpPort);
client.Credentials = new NetworkCredential(smtpSettings.SmtpUser, smtpSettings.SmtpPassword);
client.EnableSsl = true;
var mailMessage = new MailMessage
{
From = new MailAddress(smtpSettings.SmtpFrom),
Subject = subject,
Body = body,
IsBodyHtml = isHtml
};
mailMessage.To.Add(to);
await client.SendMailAsync(mailMessage);
}
}