Reputation: 1505
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);
}
Upvotes: 0
Views: 4375
Reputation: 5102
Consider FluentEmail.Core which makes replacing tokens in a string used to send email simple.
Here is an example where email.Data.Body
becomes the body for an 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
}
}
Upvotes: 1
Reputation: 1505
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);
}
Upvotes: 0