Use Razor views as email templates inside a Web Forms app

偶尔善良 提交于 2019-12-05 06:54:45

问题


I have an asp.net Web Forms application that needs to send emails. I like the Razor syntax and as you can use Razor outside of MVC I thought I'd try and use that. I've seen that you can programmatically pass a template string to razor but I'd like to keep my razor templates as separate .cshtml files.

Does anyone have any simple, idiot-proof advice as to how to do this? I've tried to load them from file like this:

UserDetails userDetails = new UserDetails {Name = "Fred"};
string template = File.OpenText("Email/UserDetailsEmail.cshtml").ReadToEnd();            
string messageText = Razor.Parse(template, userDetails);

All to no avail. There's an exception finding the file. I'm using the razorengine dll.

I have everything else working, the smtp server etc, just not the views.

Any help appreciated.


回答1:


You need to get the full path to the file; relative paths will end up being relative to the wrong location.

Write

File.OpenText(Server.MapPath("~/Email/UserDetailsEmail.cshtml"))



回答2:


I would use the MVCMailer tool which you can setup with Nuget and has scaffolding for creating the views.

It is a very well written app and can be added to yours easily:

https://github.com/smsohan/MvcMailer

http://www.codeproject.com/KB/aspnet/MvcMailerNuGet.aspx



来源:https://stackoverflow.com/questions/6031474/use-razor-views-as-email-templates-inside-a-web-forms-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!