Send-Email-CSharp/ConsoleApp1/MailService.cs
Jonas Hinterdorfer 45e86fd063 made async
2025-03-11 21:42:48 +01:00

67 lines
2.5 KiB
C#

using System.Net;
using System.Net.Mail;
namespace ConsoleApp1;
public class MailService(SmtpSettings smtpSettings)
{
/// <summary>
/// Sends a plain text email to the specified recipient.
/// </summary>
/// <param name="to">The recipient's email address.</param>
/// <param name="subject">The subject of the email.</param>
/// <param name="body">The body of the email.</param>
public async Task SendEmailText(string to, string subject, string body)
{
await SendEmailInternal(to, subject, body, isHtml: false);
}
/// <summary>
/// Sends an HTML email to the specified recipient using a file as the body.
/// </summary>
/// <param name="to">The recipient's email address.</param>
/// <param name="subject">The subject of the email.</param>
/// <param name="filePath">The file path of the HTML file to be used as the body of the email.</param>
/// <param name="replacements">Optional dictionary of placeholder replacements to be applied to the HTML body.</param>
public async Task SendEmailHtmlFile(string to, string subject, string filePath,
Dictionary<string, string>? 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);
}
/// <summary>
/// Sends an email to the specified recipient.
/// </summary>
/// <param name="to">The recipient's email address.</param>
/// <param name="subject">The subject of the email.</param>
/// <param name="body">The body of the email.</param>
/// <param name="isHtml">Indicates whether the body of the email is HTML.</param>
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);
}
}