Back ASP.NET MVC View as HTML file for use in email template

I am creating an application that will send user emails to end users.

I created an HTML template from which emails will be created.

I currently have a template populated with tags as placeholders for custom content ...

|Text-Placeholder|

I return the html file as a string to my CreateEMail method:

string html = System.IO.File.ReadAllText(Server.MapPath("~/EmailTemplates/emailTemplate.html"));

And then using String.Replace to replace in custom text / content

html = html.Replace("|Name-Placeholder|", username);

I am curious if there is a method that would allow me to create a template in the form of a RazorView, strictly typed as a ViewModel, which will model the user text / content and return the view as an HTML file or directly as a string to pass to my body property SMTPClient instance for sending to user?

Has anyone done something similar or similar?

+5
source share
4 answers

Take a look at these libraries:

There is an ActionMailer. Inspired by Ruby ActionMailer.

ActionMailer.Net ASP.NET MVC. . HTML, , ?

http://nuget.org/packages/ActionMailer

, , Razor , . . : https://bitbucket.org/swaj/actionmailer.net/wiki/Home

:

public class MailController : MailerBase
{
    public EmailResult VerificationEmail(User model)
    {
        To.Add(model.EmailAddress);
        From = "no-reply@mycoolsite.com";
        Subject = "Welcome to My Cool Site!";
        return Email("VerificationEmail", model);
    }
}

:

@using ActionMailer.Net
@model User
@{
    Layout = null;
}
Welcome to My Cool Site, @Model.FirstName. We need you to verify your email.
Click this nifty link to get verified!

:

MvcMailer MVC-

http://nuget.org/packages/MvcMailer
https://github.com/smsohan/MvcMailer

+10

, Html . , , . LoadControl Asp.net:

public static string RenderPartialToString(ControllerContext context, string partialViewName, ViewDataDictionary viewData, TempDataDictionary tempData)
{
    var viewEngineResult = ViewEngines.Engines.FindPartialView(context, partialViewName);

    if (viewEngineResult.View != null)
    {
        var stringBuilder = new StringBuilder();
        using (var stringWriter = new StringWriter(stringBuilder))
        {
            using (var output = new HtmlTextWriter(stringWriter))
            {
                ViewContext viewContext = new ViewContext(context, viewEngineResult.View, viewData, tempData, output);
                viewEngineResult.View.Render(viewContext, output);
            }
        }

        return stringBuilder.ToString();
    }

    //return string.Empty;
    throw new FileNotFoundException("The view cannot be found", partialViewName);
}

//The welcome email is in the Shared/Email folder
string partialViewHtml = EmailHelpers.RenderPartialToString(this.ControllerContext, "Email/Welcome", new ViewDataDictionary(modelForPartialView), new TempDataDictionary());
0

, !.

, ? ( )
ControllerContext , Controller

:

ThreadPool.QueueUserWorkItem(_ =>
{
    var model = new TestMailModel() { Sender = "yakirmanor", Recipient = "yakirmanor@notrealmail.com", Description = "some desc" };
    string test1 = ControllerExtensions.RenderView("Mail", "TestMail", model);
    string test2 = this.RenderView("TestMail", model);
    string test3 = this.RenderView(model);
    // now send the mail
    //MailHelper.SendEmail("yakirmanor@notrealmail.com", "subject", test1, "username", "password");
});

, TestMail Mail, TestMail .

public static class ControllerExtensions
{
    public static string RenderView(this Controller controller, object model)
    {
        string viewName = controller.ControllerContext.RouteData.Values["action"].ToString();
        string controllerName = controller.ControllerContext.RouteData.Values["controller"].ToString();
        return RenderView(controllerName, viewName, model);
    }

    public static string RenderView(this Controller controller, string viewName, object model)
    {
        string controllerName = controller.ControllerContext.RouteData.Values["controller"].ToString();
        return RenderView(controllerName, viewName, model);
    }

    public static string RenderView(string controllerName, string viewName, object viewData)
    {
        //Create memory writer
        var writer = new StringWriter();

        var routeData = new RouteData();
        routeData.Values.Add("controller", controllerName);

        //Create fake http context to render the view
        var fakeRequest = new HttpRequest(null, "http://tempuri.org", null);
        var fakeResponse = new HttpResponse(null);
        var fakeContext = new HttpContext(fakeRequest, fakeResponse);
        var fakeControllerContext = new ControllerContext(new HttpContextWrapper(fakeContext), routeData, new FakeController());

        var razorViewEngine = new RazorViewEngine();
        var razorViewResult = razorViewEngine.FindView(fakeControllerContext,viewName,"",false);

        var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, new ViewDataDictionary(viewData), new TempDataDictionary(), writer);
        razorViewResult.View.Render(viewContext, writer);

        return writer.ToString();
    }
}

,

public class TestMailModel
{
    public string Sender { get; set; }
    public string Recipient { get; set; }
    public string Description { get; set; }
}

class FakeController : ControllerBase
{
    protected override void ExecuteCore() { }
}

:

@model Phytech.PhyToWeb.Controllers.TestMailModel
@{
Layout = null;
}
<table cellpadding="8" cellspacing="0" style="width: 100%!important; background: #ffffff; margin: 0; padding: 0" border="0">
    <tbody><tr><td valign="top">
    Hi @Model.Recipient youve got mail from @Model.Sender about @Model.Description
    </td></tr></tbody>
</table>
0

as a small suggestion, instead of placeholders, use resources. you create a resource file, say, in the ~ / Content directory called EMail.resx and add your tokens to it. in a view, you can refer to them as follows: @EMail.Nameand @EMail.Address. the advantage is that if tomorrow you need to send mail in french, you will create EMail.fr.resx with all the tokens, and you will end

0
source

All Articles