Search code examples
c#smtpclientmailmessage

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. 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.

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

        var message = new MailMessage();
        message.From = new MailAddress("[email protected]", "Test sender");
        message.To.Add(new MailAddress("[email protected]", "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);
    }

Solution

  • 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):

        private async Task SendMail() {
            var client = new SmtpClient();
            client.Host = "host here";
            client.Port = 123;
    
            var message = new MailMessage();
            message.From = new MailAddress("[email protected]", "Test sender");
            message.To.Add(new MailAddress("[email protected]", "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);
        }