【问题标题】:How to replace the place holder with the dynamic text in the HTML Email template using string.Format()如何使用 string.Format() 将占位符替换为 HTML 电子邮件模板中的动态文本
【发布时间】:2020-10-22 06:04:28
【问题描述】:

我有一个包含 CSS(不是内联 CSS)的电子邮件模板,我想动态替换正文。我尝试了以下方法来避免出现无效内容错误。

string htmlBody = builder.HtmlBody.Replace("{", "{{").Replace("}", "}}");
string body = string.Format(htmlBody, dynamictext);

 using (var client = new AmazonSimpleEmailServiceClient("AccessKey", "SecretAccess",RegionEndpoint.USWest2))
            {
                var response = new SendEmailResponse();
                var emailRequest = new SendEmailRequest()
                {
                    Source = "from email ID",
                    Destination = new Destination(),
                    Message = new Amazon.SimpleEmail.Model.Message()
                };

                emailRequest.Destination.ToAddresses.Add(EmailId);
                emailRequest.Message.Subject = new Content("subject");
                emailRequest.Message.Body = new Amazon.SimpleEmail.Model.Body(new Content(body));

                try
                {
                    var x = await client.SendEmailAsync(emailRequest);
                    return 1;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    return 0;
                }
            }


但动态内容并未在 HTML 模板中被替换,它显示为 {{{0}}},表示替换 {0} 处的占位符值。

以下是正文内容示例 你好 FirstName LastName(这个字段我想替换为我放置了 {0} 占位符),

恭喜!! 您的帐户已成功创建!

要访问您的帐户,请访问 {1} 或从 payzli.com 主页单击登录。

谁能告诉我我哪里做错了。

【问题讨论】:

  • 您是否阅读过[asp.net][asp.net-core] 的标签说明?尤其是[asp.net] 的最后一部分:“不要使用这个标签来回答有关 ASP.NET Core 的问题 - 请改用 [asp.net-core]。”(来源:stackoverflow.com/tags/asp.net/info)跨度>
  • 如果htmlBody 中的占位符不是文字字符串"{0}",那么string.Format 将无法使用它。
  • 也许你在这样做的时候就明白了:string htmlBody = builder.HtmlBody.Replace("{", "{{").Replace("}", "}}").Replace("{{0}}", "{0}");
  • @Silvermind 谢谢,我尝试双重替换它并为我工作。

标签: c# html


【解决方案1】:

不确定你想做什么;但你可以这样做:

string htmlBody = "a:link {{ color:  {0}; }}";
string dyn = "pink";
string Body = string.Format(htmlBody, dyn);
Console.WriteLine(Body);

输出将是

a:link { color:  pink; }

【讨论】:

    猜你喜欢
    • 2018-11-10
    • 2014-03-01
    • 2015-10-10
    • 2018-12-05
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 2013-10-26
    相关资源
    最近更新 更多