What is the best way to create a dynamic email template that can be modified without changing code in C# .net MVC?
Every question that starts with "What is the best way to" is probably too broad or opinion-based.
In my vision, you could create a table (field name on the right, sample data on left)
id: 1
from: @@sysadress@@
to: @@useremail@@
subject: Trnasaction completed
body: Here goes your html body filled with @@data@@
... more fields as needed ...
see @@these things@@ - these would be your placeholders for dynamic text.
In your action table you will add a column, something like actionMessage and link it to Message
table. Even better is to create Action_Message
table.
Id, ActionId, MessageId, ActionStatus
This will allow to send different messages depending if your action failed, completed or postponed, or whatever.
So, this could be one way. But you will not likely to find "the best way". Every best way can be improved upon. But this will definitely achieve your main goal - change messages without recompilation.
Can I set up HTML/Email Templates with ASP.NET?
There's a ton of answers already here, but I stumbled upon a great article about how to use Razor with email templating. Razor was pushed with ASP.NET MVC 3, but MVC is not required to use Razor. This is pretty slick processing of doing email templates
As the article identifies, "The best thing of Razor is that unlike its predecessor(webforms) it is not tied with the web environment, we can easily host it outside the web and use it as template engine for various purpose. "
Generating HTML emails with RazorEngine - Part 01 - Introduction
Leveraging Razor Templates Outside of ASP.NET: They’re Not Just for HTML Anymore!
Smarter email templates in ASP.NET with RazorEngine
Similar Stackoverflow QA
Templating using new RazorEngine API
Using Razor without MVC
Is it possible to use Razor View Engine outside asp.net
Create dynamic code with templates based on options
I suppose you can use ASP.NET MVC Razor view engine to render an html to a file with the help of this question. With Razor you will get the support of dynamic view (aka template) changes, rich template syntax etc. Everything you can do when create a web site. Just render the html to a file not a response body.
Generating HTML email body in C#
You can use the MailDefinition class.
This is how you use it:
MailDefinition md = new MailDefinition();
md.From = "test@domain.example";
md.IsBodyHtml = true;
md.Subject = "Test of MailDefinition";
ListDictionary replacements = new ListDictionary();
replacements.Add("{name}", "Martin");
replacements.Add("{country}", "Denmark");
string body = "<div>Hello {name} You're from {country}.</div>";
MailMessage msg = md.CreateMailMessage("you@anywhere.example", replacements, body, new System.Web.UI.Control());
Also, I've written a blog post on how to generate HTML e-mail body in C# using templates using the MailDefinition class.
Asp.Net MVC 3 Editor for dynamic property
Dynamics don't fit the bill nicely with ASP.NET MVC. They remind me about ViewBag
and I hate ViewBag
from the very deep fabrics of my body. So I would take a different approach.
Let's take for example the following model:
public class Criterion
{
public string Text { get; set; }
public object Value { get; set; }
}
Value could be any type that you wish to handle.
Now you could have a controller which populates this model:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new[]
{
new Criterion { Text = "some integer", Value = 2 },
new Criterion { Text = "some boolean", Value = true },
new Criterion { Text = "some string", Value = "foo" },
};
return View(model);
}
}
and then a corresponding view:
@model IList<Criterion>
@using (Html.BeginForm())
{
for (int i = 0; i < Model.Count; i++)
{
<div>
@Html.LabelFor(x => x[i], Model[i].Text)
@Html.EditorFor(x => x[i].Value, "Criterion_" + Model[i].Value.GetType().Name)
</div>
}
<button type="submit">OK</button>
}
Now for each type that you want to handle you could define a corresponding editor template:
~/Views/Shared/EditorTemplates/Criterion_String.cshtml
:
@model string
@Html.TextBoxFor(x => x)
~/Views/Shared/EditorTemplates/Criterion_Boolean.cshtml
:
@model bool
@Html.CheckBoxFor(x => x)
~/Views/Shared/EditorTemplates/Criterion_Int32.cshtml
:
@model int
@{
var items = Enumerable
.Range(1, 5)
.Select(x => new SelectListItem
{
Value = x.ToString(),
Text = "item " + x
});
}
@Html.DropDownListFor(x => x, new SelectList(items, "Value", "Text", Model))
Obviously displaying this model in the view is only the first step. I suppose that you will want to get the values that the user entered back in the POST controller action for some processing. In this case some small adaptations are necessary. We need to add a custom model binder that will be able to instantiate the correct type at runtime and include the concrete type as hidden field for each row. I have already shown an example in this post
. Also notice in this example that I used a base class instead of directly working with the object
type.
system.net.mail editing mail content
You could store html in an XML file and populate the content via string.Format
like so: -
<?xml version="1.0" encoding="utf-8" ?>
<Email>
<FromAddress>from</FromAddress>
<ToAddress>to</ToAddress>
<Subject>subject line</Subject>
<EmailBody>
<![CDATA[
<html>
<head>
<title>Customer</title>
</head>
<div valign="top">
<font color="#666666" face="Arial, Helvetica, sans-serif, Verdana" size="2">
<p>Hello user.</p>
<p><strong>This is your ID in the system: </strong>{0}<br />
<strong>You chose option: </strong>{1}<br /></p>
</font>
</div>
</html>
]]>
</EmailBody>
</Email>
Code (populate and send): -
int custId = //provide customer id
string option = //customers selected option
string custEmail = //customers email
MailMessage mail = GetHtmlEmail();
string message = string.Format(mail.Body, custId, option);
mail.IsBodyHtml = true;
mail.Body = message;
using (SmtpClient smtp = new SmtpClient())
{
smtp.Send(mail);
}
Reading in the email markup + setting some properties of the mail object: -
private MailMessage GetHtmlEmail()
{
MailMessage mail = new MailMessage();
XmlTextReader xReader = new XmlTextReader(Server.MapPath("PATH TO EMAIL.XML"));
while (xReader.Read())
{
switch (xReader.Name)
{
case "ToAddress":
mail.To.Add(xReader.ReadElementContentAs(typeof(string), null).ToString());
break;
case "FromAddress":
mail.From = new MailAddress(xReader.ReadElementContentAs(typeof(string), null).ToString());
break;
case "Subject":
mail.Subject = xReader.ReadElementContentAs(typeof(string), null).ToString();
break;
case "EmailBody":
mail.Body = xReader.ReadElementContentAs(typeof(string), null).ToString();
break;
default:
break;
}
}
return mail;
}
Edit* If you don't want this <strong>You chose option: </strong>{1}<br />
to appear AT ALL if the customer chose no option, then you could do this (though a bit hacky): -
if(!string.IsNullOrEmpty(option))
{
option = string.Format("<strong>You chose option: </strong>{1}<br />", option);
}
else
{
option = string.Empty;
}
Then pass it in as normal: -
string message = string.Format(mail.Body, custId, option);
Making sure to replace this line in the markup <strong>You chose option: </strong>{1}<br />
with {1}
Related Topics
Newtonsoft.Json Serializeobject Without Escape Backslashes
Most Efficient Way to Compare Two Ienumerables (Or Lists) in Linq
How to Insert 10 Million Records in the Shortest Time Possible
Get the Index of the Nth Occurrence of a String
How to Wait Until Task Is Finished in C#
How to Download Image from Url
Adding an Incremental Number to Duplicate String
Asp.Net MVC - How to Call Void Controller Method Without Leaving the View
How to Autosize the Height and the Width of C# Windows Form
How to Upload a Excel File to SQL Database Table Using C# Windows Form Application
Select Multiple Fields Group by and Sum
C# Lamba With Datetime and Between
Asp.Net Core API Post Parameter Is Always Null
How to Turn Off Brackets/Quotes Auto-Completion in Visual Studio