views:

89

answers:

2

In an ASP.NET MVC application, how should the sending of emails be handled? I've been thinking about this, and I really like the idea of handling it in an MVC-oriented way (it is an MVC application, after all.)

What I mean is that the email that gets delivered to the user is really just a view that should have a model passed to it. This raises some questions: How should we deliver views to both the requesting browser and an SMTP server at the same time, when an action is executed? Does the framework have any facilities to support this? If not, is there some 3rd party release/guidance for this sort of functionality?

The alternatives to treating email sending in an MVC way are:

  • Email sending code shows up in the controller's action methods.
  • Email sending is a behavior of the Model objects.

How are you handling the sending of emails in your ASP.NET MVC applications? What do you think about an MVC-oriented approach?

+4  A: 

Usually when you'd need a new result type, you would program a new MyResult object that would inherit from ActionResult. This way your action method would be free to choose the result type that was indicated, and the View Engine would simply call the ExecuteResult() method on the new result type, which would hold the logic on how to render the data.

However, since what you're doing sounds like you just want to get HTML from a View and email it (it's the same result type as for the web browser), the answers to this question should cover it in depth. Note that the answers with the code for MVC 2.0 are the best way to go, since they added the "render a view to a string" functionality into the second release due to popular demand.

Your question is a good one, as I would highly recommend an MVC approach to any output from your program. Sending a view to email is conceptually no different than sending a view to any other output type (PDF, mobile browser, SMS), and by building pluggable view outputs, you have an easy way to support expansion of the usage of your app.

womp
A: 

Its a interesting question. You can try creating a custom ActionFilterAttribute and implementing the OnResultExecuted method. From there you should be able to get hold of the output html and emailing it.

So all you would need to do is to decorate the action methods with your custom attribute and calling the view would send the output to the browser as well as emailing it.

ravi
I doubt that I would hardly, if ever, want to email the exact same thing that is sent to the browser.
Ronnie Overby