70 lines
1.9 KiB
C#
70 lines
1.9 KiB
C#
using System.Net;
|
|
using System.Net.Mail;
|
|
|
|
namespace ConsoleApp1;
|
|
|
|
public class MailService
|
|
{
|
|
private readonly SmtpSettings _smtpSettings;
|
|
|
|
public MailService(SmtpSettings smtpSettings)
|
|
{
|
|
_smtpSettings = smtpSettings;
|
|
}
|
|
|
|
public void SendEmail(string to, string subject, string body)
|
|
{
|
|
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 = true,
|
|
};
|
|
|
|
mailMessage.To.Add(to);
|
|
|
|
client.Send(mailMessage);
|
|
}
|
|
}
|
|
|
|
private void SendEmailHtml(string to, string subject, string body)
|
|
{
|
|
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 = true,
|
|
};
|
|
|
|
mailMessage.To.Add(to);
|
|
|
|
client.Send(mailMessage);
|
|
}
|
|
|
|
public void SendEmailHtmlFile(string to, string subject, string filePath, Dictionary<string, string>? replacements = null)
|
|
{
|
|
string body = System.IO.File.ReadAllText(filePath);
|
|
|
|
if (replacements is not null)
|
|
{
|
|
foreach (var replacement in replacements)
|
|
{
|
|
body = body.Replace($"{{{replacement.Key}}}", replacement.Value);
|
|
}
|
|
}
|
|
|
|
SendEmailHtml(to, subject, body);
|
|
}
|
|
|
|
} |