原文发布时间为:2011-09-15 —— 来源于本人的百度文章 [由搬家工具导入]

http://kazimanzurrashid.com/posts/use-razor-for-email-template-outside-asp-dot-net-mvc

So the ASP.NET MVC 3 RTM is out and the real icon of this release is the Razor View Engine. The best thing of Razor is that unlike its predecessor(webforms) it is not tied with the web environment, we can easily host it outside the web and  use it as template engine for various purpose. The project that I am currently working on needs to send bulk emails at various point of the application,  since the numbers can be hundreds or literary thousands I want to host it outside the web application so that it does add unnecessary overheads to the web application. In this post, I will show you you the code that I am using to generate these mails, you can download the complete code with MSpec specs from the bottom of the post.

Lets say, in your application you want to send a welcome mail to user, whenever s/he registers. To send the mail you can use the following code:

123456789101112131415publicvirtualvoidSendWelcomeMail(stringname, stringpassword, stringemail){    varmodel = new                {                    From = Configuration.FromAddress,                    To = email,                    Name = name,                    Password = password,                    LogOnUrl = Configuration.LogOnUrl()                };     varmail = TemplateEngine.Execute(Configuration.SendWelcomeMailTemplateName, model);     Sender.Send(mail);}

And here is the template that it will use to generate the actual mail content:

123456789101112131415161718@{    From = Model.From;    To.Add(Model.To);    Subject = "Welcome to my mysite.com";}<html><head>    <title>Welcome to mysite.com</title></head><body>    <p>Dear @Model.Name,</p>    <p>An account has been created for you.</p>    <p>Your account is FREE and allows you to perform bla bla features.</p>    <p>To login and complete your profile, please go to:</p>    <p><ahref="@Model.LogOnUrl">@Model.LogOnUrl</a></p>    <p>Your User ID is your email address and password is: @Model.Password</p></body></html>

The code is very simple, first we are creating an anonymous object as model, you can also use strongly typed as well as the new dynamic object, next we are using the template engine to generate the output and at last the mail object is passed to the mail sender for dispatching it. In the template the model is that we passed from the method is exposed as the dynamic object. Behind the scene the template uses a base class which has some of the common properties that we often use for setting the mail:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556publicabstractclassEmailTemplate : IEmailTemplate{    privatereadonlyStringBuilderbuffer;     [DebuggerStepThrough]    protectedEmailTemplate()    {        To = newList<string>();        ReplyTo = newList<string>();        CC = newList<string>();        Bcc = newList<string>();        Headers = newDictionary<string, string>(StringComparer.OrdinalIgnoreCase);         buffer = newStringBuilder();    }     publicstringFrom { get; set; }     publicstringSender { get; set; }     publicICollection<string> To { get; privateset; }     publicICollection<string> ReplyTo { get; privateset; }     publicICollection<string> CC { get; privateset; }     publicICollection<string> Bcc { get; privateset; }     publicIDictionary<string, string> Headers { get; privateset; }     publicstringSubject { get; set; }     publicstringBody    {        get{ returnbuffer.ToString(); }    }     protecteddynamic Model { get; privateset; }     publicvoidSetModel(dynamic model)    {        Model = model;    }     publicabstractvoidExecute();     publicvirtualvoidWrite(objectvalue)    {        WriteLiteral(value);    }     publicvirtualvoidWriteLiteral(objectvalue)    {        buffer.Append(value);    }}

It is also possible to compose a mail which contains both text and html format, so that the mail client which supports html should use the html version and the unsupported client could use the plain version. To compose a multi formatted mail you will have to use three templates the shared template will contain the common properties like From/To/Subject etc. and the other two will contain the actually body. For example, to use the above mail in multi format we will create the following templates:

Shared Template12345@{    From = Model.From;    To.Add(Model.To);    Subject = "Welcome to mysite.com";}Html Template12345678910111213<html><head>    <title>Welcome to mysite.com</title></head><body>    <p>Dear @Model.Name,</p>    <p>An account has been created for you.</p>    <p>Your account is FREE and allows you to perform bla bla features.</p>    <p>To login and complete your profile, please go to:</p>    <p><ahref="@Model.LogOnUrl">@Model.LogOnUrl</a></p>    <p>Your User ID is your email address and password is: @Model.Password</p></body></html>Text Template1234567891011Dear @Model.Name, An account has been created for you. Your account is FREE and allows you to perform bla bla features. To login and complete your profile, please go to: @Model.LogOnUrl Your User ID is your email address and password is: @Model.Password

Now, when the mail is sent it should look like the following:

123456789101112131415161718192021222324252627282930313233343536X-Sender: me@myself.comX-Receiver: jon@smith.comMIME-Version: 1.0From: me@myself.comTo: jon@smith.comDate: 15 Jan 2011 12:42:41 +0600Subject: Welcome to mysite.comContent-Type: multipart/alternative; boundary=--boundary_0_9202367d-977d-49b5-ab86-2bb3ed1bfc76  ----boundary_0_9202367d-977d-49b5-ab86-2bb3ed1bfc76Content-Type: text/htmlContent-Transfer-Encoding: base64 PGh0bWw+DQo8aGVhZD4NCiAgICA8dGl0bGU+V2VsY29tZSB0byBteXNpdGUuY29tPC90aXRsZT4NCjwvaGVhZD4NCjxib2R5Pg0KICAgIDxwPkRlYXIgSm9uIFNtaXRoLDwvcD4NCiAgICA8cD5BbiBhY2NvdW50IGhhcyBiZWVuIGNyZWF0ZWQgZm9yIHlvdS48L3A+DQogICAgPHA+WW91ciBhY2NvdW50IGlzIEZSRUUgYW5kIGFsbG93cyB5b3UgdG8gcGVyZm9ybSBibGEgYmxhIGZlYXR1cmVzLjwvcD4NCiAgICA8cD5UbyBsb2dpbiBhbmQgY29tcGxldGUgeW91ciBwcm9maWxlLCBwbGVhc2UgZ28gdG86PC9wPg0KICAgIDxwPjxhIGhyZWY9Imh0dHA6Ly9teWNvbXBhbnkuY29tL2xvZ29uIj5odHRwOi8vbXljb21wYW55LmNvbS9sb2dvbjwvYT48L3A+DQogICAgPHA+WW91ciBVc2VyIElEIGlzIHlvdXIgZW1haWwgYWRkcmVzcyBhbmQgcGFzc3dvcmQgaXM6IH4hQWdjMmQjNzwvcD4NCjwvYm9keT4NCjwvaHRtbD4=----boundary_0_9202367d-977d-49b5-ab86-2bb3ed1bfc76Content-Type: text/plainContent-Transfer-Encoding: base64 RGVhciBKb24gU21pdGgsDQoNCkFuIGFjY291bnQgaGFzIGJlZW4gY3JlYXRlZCBmb3IgeW91Lg0KDQpZb3VyIGFjY291bnQgaXMgRlJFRSBhbmQgYWxsb3dzIHlvdSB0byBwZXJmb3JtIGJsYSBibGEgZmVhdHVyZXMuDQoNClRvIGxvZ2luIGFuZCBjb21wbGV0ZSB5b3VyIHByb2ZpbGUsIHBsZWFzZSBnbyB0bzoNCg0KaHR0cDovL215Y29tcGFueS5jb20vbG9nb24NCg0KWW91ciBVc2VyIElEIGlzIHlvdXIgZW1haWwgYWRkcmVzcyBhbmQgcGFzc3dvcmQgaXM6IH4hQWdjMmQjNw==----boundary_0_9202367d-977d-49b5-ab86-2bb3ed1bfc76--

Currently it uses templates which are stored in the file system, but it is extensible enough to store the templates in other mediums like database. Like ASP.NET it compiles the templates to .NET types when first time it is requested, but it does not have the cache invalidation support like asp.net, may be I will add it in future.

That’s it for today.

Download:EmailTemplate.zip

Use Razor for Email Template outside ASP.NET MVC的更多相关文章

  1. 返璞归真 asp.net mvc (9) - asp.net mvc 3.0 新特性之 View(Razor)

    原文:返璞归真 asp.net mvc (9) - asp.net mvc 3.0 新特性之 View(Razor) [索引页][源码下载] 返璞归真 asp.net mvc (9) - asp.ne ...

  2. 7、ASP.NET MVC入门到精通——第一个ASP.NET MVC程序

    本系列目录:ASP.NET MVC4入门到精通系列目录汇总 开发流程 新建Controller 创建Action 根据Action创建View 在Action获取数据并生产ActionResult传递 ...

  3. 【ASP.NET】第一个ASP.NET MVC应用程序

    本系列目录:ASP.NET MVC4入门到精通系列目录汇总 开发流程 新建Controller 创建Action 根据Action创建View 在Action获取数据并生产ActionResult传递 ...

  4. ASP.NET MVC入门到精通——第一个ASP.NET MVC程序

    开发流程 新建Controller 创建Action 根据Action创建View 在Action获取数据并生产ActionResult传递给View. View是显示数据的模板 Url请求→Cont ...

  5. ASP.NET MVC 3 Model【通过一简单实例一步一步的介绍】

    今天主要讲Model的两个方面: 1. ASP.Net MVC 3 Model 简介 通过一简单的事例一步一步的介绍 2. ASP.Net MVC 3 Model 的一些验证 MVC 中 Model ...

  6. ASP.NET MVC 4高级编程(第4版)

    <ASP.NET MVC 4高级编程(第4版)> 基本信息 作者: (美)Jon Galloway    Phil Haack    Brad Wilson    K. Scott All ...

  7. Scaffolding Template on Asp.Net Core Razor Page

    Scaffolding Template Intro 我们知道在Asp.Net MVC中,如果你使用的EF的DBContext的话,你可以在vs中通过右键解决方案-添加控制器-添加包含视图的控制器,然 ...

  8. Asp.net MVC Razor模板引擎技巧分享

    Razor是Asp.net MVC中新的默认模板类型, 语法简单易用.这篇文章不涉及Razor的语法,主要介绍Razor的一些在MVC项目中的使用技巧,以及脱离MVC环境下,如何使用Razor. 阅读 ...

  9. A Look at the Razor View Engine in ASP.NET MVC

    The biggest architectural difference that exists between ASP.NET MVC and ASP.NET Web Forms is the ne ...

随机推荐

  1. v4l2解析

    v4l2的学习建议和流程解析: http://www.cnblogs.com/silence-hust/p/4464291.html 补充: 枚举设备所支持的image format: VIDIOC_ ...

  2. 【luogu题解】P1546 最短网络 Agri-Net

    题目 约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场.为了用最小的消费,他想铺设最短的光纤去连接所有的农场. 你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并 ...

  3. SQL初次接触

    1.SQL对大小写不敏感 2.部分SQL数据库要求结尾分号 3.分为两种DML(数据操作语言)和DDL(数据定义语言) sql中一些注意要点 1.设置主键 一般会在一个数据内设置一个主键(名字通常为i ...

  4. 自动化运维工具——ansible安装入门(一)

    一.简介 现如今有很多运维自动化的工具,如:Ansible.Puppet.saltStack.Fabric.chef.Cfengine 1. Ansible介绍 Ansible 是由 Cobbler与 ...

  5. thinkcmf5 iis+php重写配置

    TP在本机运行非常好,谁想到服务器上后,连http://www.***.com/wap/login/index都404错误了, 中间的郁闷过程不表. 解决方案分两步: 第一步: 下载rewrite_2 ...

  6. 基于django的个人博客网站建立(二)

    基于django的个人博客网站建立(二) 前言 网站效果可点击这里访问 今天主要完成后台管理员登录的状态以及关于文章在后台的处理 具体内容 首先接上一次内容,昨天只是完成了一个登录的跳转,其他信息并没 ...

  7. Python9-From-CSS-day48

    1.form表单相关内容前后端有数据交互的时候用form表单form表单提交数据的几个注意事项: 1.所有获取用户输入的标签都必须放在form表单里面 2.action 控制着往哪里提交 3.inpu ...

  8. python-01 spider原理

    用Python可以做什么?可以做日常任务,比如自动备份你的MP3:可以做网站,很多著名的网站包括YouTube就是Python写的:可以做网络游戏的后台,很多在线游戏的后台都是Python开发的.总之 ...

  9. 动态规划:HDU1789-Doing Homework again

    Doing Homework again Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Oth ...

  10. hdu5319 简单模拟

    题意很好懂,大致就是三种颜色,红和蓝一起会变绿,给个终态矩阵,问从原始状态到终态最少画几笔?  按一定规则画 思路就是记红为1,蓝为2,绿为3,先遍历绿色,针对每一块绿色进行删除,每找到一块绿色,首先 ...