Ở các loạt bài viết: Gửi Email động trong ASP.NET và send email với attachment chúng ta cũng đã được làm quen với cách giử email động sử dụng template.
Câu hỏi đặt ra là: “hổng lẻ chúng ta phải replace các tham số trong template bằng các giá trị truyền vào”, và nó có 1 thư viện hay 1 engine chuyên đảm nhận việc này cho chúng ta hok?
Nvelocity là câu trả lời, Nvelocity là 1 template engine cho phép chúng ta merged giữa template và các giá trị, Nvelocity cung cấp 3 dạng cho phép chúng ta xử lý: template file, template được embed vào resource và in-memory template.
Trong bài blog này mình sẽ chỉ hướng dẫn các thao tác làm việc với dạng file template.
Đầu tiên chúng ta download version mới nhất của Nvelocity tại đây v.1.6.1 beta, sau đó get code 2 bài viết Gửi Email động trong ASP.NET hoặc send email với attachment.
Chỉnh sửa file Contact.htm trong thư mục template bằng:
<p>Người gửi: $sender</p>
<p>Thư điện tử: $email</p>
<p>Nội dụng: $content</p>
<p>Ngày giờ gửi: $dateTime</p>
Tham khảo cú pháp template của Nvelocity tại http://velocity.apache.org/engine/devel/vtl-reference-guide.html
Thạo 1 phương thức GenerateContent dùng để generate content, với 2 tham số bào gồm template file (đường dẫn tập tin template) và các thuộc tính dạng IDictionary
CS
public string GenerateContent(string templateFileName, IDictionary<string, object> properties)
{
string directoryName = Path.GetDirectoryName(templateFileName);
if (String.IsNullOrEmpty(directoryName))
directoryName = ".";
string templateDir = Path.GetFullPath(directoryName);
VelocityEngine engine = new VelocityEngine();
ExtendedProperties props = new ExtendedProperties();
props.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, directoryName);
props.AddProperty("input.encoding", "utf-8");
props.AddProperty("output.encoding", "utf-8");
engine.Init(props);
VelocityContext context = new VelocityContext();
Template template = engine.GetTemplate(Path.GetFileName(templateFileName), new UTF8Encoding(false).WebName);
foreach (string strKey in properties.Keys)
{
context.Put(strKey, properties[strKey]);
}
using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
{
template.Merge(context, writer);
return writer.ToString();
}
}
Public Function GenerateContent(ByVal templateFileName As String, ByVal properties As IDictionary(Of String, Object)) As String
Dim directoryName As String = Path.GetDirectoryName(templateFileName)
If [String].IsNullOrEmpty(directoryName) Then
directoryName = "."
End If
Dim templateDir As String = Path.GetFullPath(directoryName)
Dim engine As New VelocityEngine()
Dim props As New ExtendedProperties()
props.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, directoryName)
props.AddProperty("input.encoding", "utf-8")
props.AddProperty("output.encoding", "utf-8")
engine.Init(props)
Dim context As New VelocityContext()
Dim template As Template = engine.GetTemplate(Path.GetFileName(templateFileName), New UTF8Encoding(False).WebName)
For Each strKey As String In properties.Keys
context.Put(strKey, properties(strKey))
Next
Using writer As New StringWriter(CultureInfo.InvariantCulture)
template.Merge(context, writer)
Return writer.ToString()
End Using
End Function
Dictionary lưu trữ giá trị dạng key-value, cái mà chúng ta cần cũng chính là tham số và giá trị của template.
Thay đổi function Send
try
{
Dictionary<string, object> emailDics = new Dictionary<string, object>();
emailDics.Add("sender", TextBoxName.Text);
emailDics.Add("email", TextBoxEmail.Text);
emailDics.Add("content", TextBoxContent.Text);
emailDics.Add("dateTime", DateTime.Now.ToShortDateString());
string templatePath = AppDomain.CurrentDomain.BaseDirectory + "template\\Contact.htm";
string ret = GenerateContent(templatePath, emailDics);
Response.Write(SendMail("Liên hệ khách hàng", ret, "quachngochoangnguyen@gmail.com", true, true));
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
VB.NET:
Try
Dim emailDics As New Dictionary(Of String, Object)
emailDics.Add("sender", TextBoxName.Text)
emailDics.Add("email", TextBoxEmail.Text)
emailDics.Add("content", TextBoxContent.Text)
emailDics.Add("dateTime", DateTime.Now.ToShortDateString())
Dim templatePath As String = AppDomain.CurrentDomain.BaseDirectory + "template\\Contact.htm"
Dim ret As String = GenerateContent(templatePath, emailDics)
Response.Write(SendMail("Liên hệ khách hàng", ret, TextBoxEmail.Text.Trim(), True, True))
Catch ex As System.Exception
Response.Write(ex.Message)
End Try
History version:
25/07/2010: first release with c# code
28/07/2010: adding vb.net code
Hope this help!