63 lines
2.3 KiB
C#
63 lines
2.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace BulkArchiveMailer.Core
|
|
{
|
|
/// <summary>
|
|
/// Minimal placeholder substitution for Subject/BodyHtml templates.
|
|
/// Deliberately simple (no conditionals/loops) - templates are short,
|
|
/// hand-edited strings, not a general templating language.
|
|
/// </summary>
|
|
public static class TemplateEngine
|
|
{
|
|
private static readonly Regex PlaceholderPattern = new Regex(@"\{(?<name>[A-Za-z0-9_]+)\}", RegexOptions.Compiled);
|
|
|
|
/// <summary>
|
|
/// Replaces every "{Name}" placeholder with the matching value from
|
|
/// <paramref name="values"/> (case-insensitive lookup). Unknown
|
|
/// placeholders are left untouched rather than throwing, so a typo
|
|
/// in a hand-edited template shows up visibly in the preview
|
|
/// instead of crashing the scan.
|
|
/// </summary>
|
|
public static string Render(string template, IDictionary<string, string> values)
|
|
{
|
|
if (string.IsNullOrEmpty(template))
|
|
{
|
|
return template ?? string.Empty;
|
|
}
|
|
|
|
return PlaceholderPattern.Replace(template, match =>
|
|
{
|
|
var name = match.Groups["name"].Value;
|
|
foreach (var kvp in values)
|
|
{
|
|
if (string.Equals(kvp.Key, name, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return kvp.Value ?? string.Empty;
|
|
}
|
|
}
|
|
|
|
return match.Value; // leave "{Unknown}" as-is
|
|
});
|
|
}
|
|
|
|
/// <summary>Renders both Subject and BodyHtml of a template for one recipient.</summary>
|
|
public static MailTemplate Render(MailTemplate template, string login, string email)
|
|
{
|
|
var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
|
{
|
|
["Login"] = login ?? "",
|
|
["Email"] = email ?? "",
|
|
["Date"] = DateTime.Now.ToString("dd.MM.yyyy"),
|
|
};
|
|
|
|
return new MailTemplate
|
|
{
|
|
Subject = Render(template?.Subject ?? "", values),
|
|
BodyHtml = Render(template?.BodyHtml ?? "", values),
|
|
};
|
|
}
|
|
}
|
|
}
|