Here is my own suggestion. IF you are using MVC, create an independent view for your emails (let's say myemail.cs) and assign a model to it (myemailModel).
Here is your myemailModel class
public class myemailModel {
public string Username{get;set;}
public IList<Data> data{get;set;}
public class Data{
public string Name{get;set;}
public int Age{get;set;}
}
}
So your view would look like this:
@model myemailModel
<html>
<body>
Hello @Model.Email!
@if (Model.data !=null && Model.data.count() >0)
{
<table class="tblCss">
<tr>
<th> Name </th>
<th> Age </th>
</tr>
foreach (var i in Model.data)
{
<tr>
<td>@i.Name</td>
<td>@i.Age</td>
</tr>
}
</table>
}
</body>
</html>
Finally, you need to render the view into a string. Use the following method (Render a view as a string):
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View,
ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
And call the above method to get the body:
string body = RenderRazorViewToString("myemail", new myemailModel {
Username="foo",
data = new List<myemailModel>{
// fill it
}
});