You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何替换HTML邮件模板变量?是否有内置实现方式?

解决方案

.NET 并没有提供直接替换邮件模板变量的内置功能,你需要先将模板文件内容读取为字符串,完成变量替换后再生成邮件内容(包括使用AlternateView)。AlternateView的作用是为邮件添加不同格式的内容(比如同时支持HTML和纯文本),本身不具备模板渲染能力。

具体实现步骤

  • 读取HTML模板文件的内容到字符串
  • 替换字符串中的变量(可根据变量复杂度选择string.Replace、string.Format或正则表达式)
  • 将替换后的字符串转换为AlternateView(或直接设置MailMessage.Body)

修改后的代码示例

private async Task SendMail()
{
    var client = new SmtpClient();
    client.Host = "host here";
    client.Port = 123;

    var message = new MailMessage();
    message.From = new MailAddress("from@test.com", "Test sender");
    message.To.Add(new MailAddress("to@test.com", "Test receiver"));
    message.SubjectEncoding = Encoding.UTF8;
    message.BodyEncoding = Encoding.UTF8;
    message.Subject = "Test subject";

    // 1. 读取模板文件内容
    string templateContent = File.ReadAllText("testFile.html", Encoding.UTF8);
    // 2. 替换变量
    string renderedContent = templateContent.Replace("<%= name %>", "测试用户");
    // 3. 创建替换后的AlternateView
    var htmlView = AlternateView.CreateAlternateViewFromString(
        renderedContent,
        Encoding.UTF8,
        "text/html"
    );

    message.AlternateViews.Add(htmlView);

    // 建议await异步方法,避免操作未完成就结束
    await client.SendMailAsync(message);
}

额外说明

如果模板中有多个变量,string.Replace会比较繁琐,你可以改用string.Format(需要将模板占位符调整为{0}、{1}这类格式),或者使用插值字符串。如果需要复杂模板逻辑(比如循环、条件判断),可以引入第三方模板库(如RazorEngine),但这不属于.NET内置功能。

内容的提问来源于stack exchange,提问作者Johan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 13:05:25