简体   繁体   English

使用 html email 模板并替换 MailMessage 中的变量

[英]Use html email template and replace variables in MailMessage

I have an html email template in a file and want to replace variables in the template before sending the email.我在一个文件中有一个 html email 模板,想在发送 email 之前替换模板中的变量。 Is there any easy/built-in way of doing that or do I have to read the file contents as a string and replace them manually?是否有任何简单/内置的方法可以做到这一点,或者我必须将文件内容作为字符串读取并手动替换它们? It feels like AlternateView is made for loading a template but I can't find a way to replace variables.感觉 AlternateView 是为加载模板而设计的,但我找不到替换变量的方法。

    private void 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 reciever"));
        message.SubjectEncoding = Encoding.UTF8;
        message.BodyEncoding = Encoding.UTF8;
        message.Subject = "Test subject";

        // testFile.html contents:
        //
        // <html>
        //  <body>
        //   <h1><%= name %></h1>          <-- Name should be replaced
        //  </body>
        // </html>
        var alternativeView = new AlternateView("testFile.html", new System.Net.Mime.ContentType("text/html"));

        message.AlternateViews.Add(alternativeView);

        client.SendMailAsync(message);
    }

you have to read template from file and then apply replace您必须从文件中读取模板,然后应用替换

Apparently there's no built-in way to do this so I ended up reading the file as a string and replacing them manually (the reason I use AlternateView is because in the original code I have both an html and plain text body):显然没有内置的方法可以做到这一点,所以我最终将文件作为字符串读取并手动替换它们(我使用 AlternateView 的原因是因为在原始代码中我有 html 和纯文本正文):

    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 reciever"));
        message.SubjectEncoding = Encoding.UTF8;
        message.BodyEncoding = Encoding.UTF8;
        message.Subject = "Test subject";

        // testFile.html contents:
        //
        // <html>
        //  <body>
        //   <h1><%= name %></h1>          <-- Name should be replaced
        //  </body>
        // </html>

        var content = await File.ReadAllTextAsync("testFile.html");
        content = content.Replace("<%= name %>", "Superman");
        var alternativeView = AlternateView.CreateAlternateViewFromString(content, new ContentType(MediaTypeNames.Text.Html));

        message.AlternateViews.Add(alternativeView);

        await client.SendMailAsync(message);
    }

Consider FluentEmail.Core which makes replacing tokens in a string used to send email simple.考虑FluentEmail.Core ,它使替换用于发送 email 的字符串中的令牌变得简单。

Here is an example where email.Data.Body becomes the body for an email.这是一个示例,其中email.Data.Body成为 email 的主体。

在此处输入图像描述

internal class Program
{
    static void Main(string[] args)
    {

        /*
         * Can come from a file
         */
        string template = @"
<html>
 <body>
  <h1><%= ##Name## %></h1>
  <p>On <%=##Date##%> you are required to change your password</p>
  <p>Any questions contact ##Contact##</p>
 </body>
</html>
";

        var email = Email
            .From("fromEmail")
            .To("toEmail")
            .Subject("subject")
            .UsingTemplate(template, new
            {
                Name = "Mary Sue", 
                Date = new DateTime(2022,10,12).ToString("d"),
                Contact = "Bill Jones (504) 999-1234"
            });

        Console.WriteLine(email.Data.Body); // for body of email

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM