3

I have an ActionResult in my controller that I want to send an HTML email from, the body of that email is generated by a view. Rather than having 2 actionresults methods in my controller can I just get the result of the view when passed my model and avoid it being sent to the browser?

2

2 Answers 2

8

MvcMailer is a brilliant little project that supports generating emails using MVC views. It is available as a NuGet package.

In order to render a view to a string instead of response use this code (relativePath points to your view file):

        var content = string.Empty;
        var view = ViewEngines.Engines.FindView(ControllerContext, relativePath, null);
        using (var writer = new StringWriter())
        {
            var context = new ViewContext(ControllerContext, view.View, ViewData, TempData, writer);
            view.View.Render(context, writer);
            writer.Flush();
            content = writer.ToString();
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Api.ControllerContext is System.Web.Http.Controllers.HttpControllerContext and FindView needs System.Web.Mvc.ControllerContext...
4

Take a look at the open source Postal project it's available view NuGet.

Postal lets you create emails using regular MVC views.

Andrew Davey done a presentation on Generating email with View Engines using Postal at mvcConf 2

Or alternatively this blog post shows you a simple way.

1 Comment

I believe MVC 4 is not yet supported with Postal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.