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:
How are you handling the sending of emails in your ASP.NET MVC applications? What do you think about an MVC-oriented approach?
For sending mail from ASP.NET MVC we use the "System. Net.Mail" namespace.
First: Edit Your AppStart Page SmtpPort: The port the server will use to send SMTP transactions (emails). EnableSsl: True, if the server should use SSL (Secure Socket Layer) encryption. UserName: The name of the SMTP email account used to send the email. Password: The password of the SMTP email account.
In Razor, `@` symbol is used to transition from HTML to C#. To escape an '@' symbol in razor markup, use two '@' symbols.
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.
Did you take a look at MvcMailer? See the NuGet package here and the project documentation
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With