简单实现邮件模板功能
系统中经常有需要发送提醒邮件的需求,而且邮件类型和内容往往又不同,有些还需要跟业务字段做关联。这种情况下,就需要用到邮件模板功能,可以通过在模板中定义业务字段标记,通过模板引擎或自定义代码来实现这些字段的填充。
下面是一个自己写的简单的,字符串替换方式实现的邮件模板功能。代码如下:
public class DynamicTemplateBinder { /// <summary> /// 邮件模板替换 /// </summary> /// <param name="template"></param> /// <param name="model"></param> /// <returns></returns> public static string RanderTemplate(string template, object model) { string content = template; if (string.IsNullOrEmpty(template)) { } // 获取对象的类型 Type type = model.GetType(); var properties = type.GetProperties(); // 匹配$$FieldName$$ Regex regex = new Regex(@"\$\$([a-zA-Z_\.][a-zA-Z0-9_\.]*)\$\$"); var matches = regex.Matches(template); foreach (Match match in matches) { // Console.WriteLine(match.Groups[1].Value); // 输出不含大括号的字段名 string propertyName = match.Groups[1].Value; var propertyInfo = type.GetProperty(propertyName); var propVal = string.Empty; if (propertyInfo != null) { var propertyValue = propertyInfo.GetValue(model, null); if (propertyValue != null) { propVal = propertyValue.ToString(); } } content = content.Replace(match.Value, propVal); } return content; } string RanderLoop(string template, object model) { // 获取对象的类型 Type type = model.GetType(); string content = template; Regex regex = new Regex(@"<<LoopStart[^>]*data=(.*?)>>(.*)<<LoopEnd>>"); var matches = regex.Matches(template); foreach (Match match in matches) { string loopContent = string.Empty; var matchVal = match.Value; var loopPropertyName = match.Groups[1].Value; var loopPropertyInfo = type.GetProperty(loopPropertyName); if (loopPropertyInfo != null) { var loopProperyValue = loopPropertyInfo.GetValue(model, null); if (loopProperyValue != null && loopProperyValue is IEnumerable) { string loopTemp = string.Empty; foreach (var item in loopProperyValue as IEnumerable) { var itemType = item.GetType(); loopTemp = match.Groups[2].Value; if (loopTemp != null) { string itemContent = loopTemp; // 匹配$$FieldName$$ Regex fieldReg = new Regex(@"\$\$([a-zA-Z_\.][a-zA-Z0-9_\.]*)\$\$"); var fieldMatches = fieldReg.Matches(loopTemp); foreach (Match fm in fieldMatches) { string propertyName = fm.Groups[1].Value; var propertyInfo = itemType.GetProperty(propertyName); var propVal = string.Empty; if (propertyInfo != null) { var propertyValue = propertyInfo.GetValue(item, null); if (propertyValue != null) { propVal = propertyValue.ToString(); } } itemContent = itemContent.Replace(fm.Value, propVal); } loopContent += itemContent; } } } } content = template.Replace(matchVal, loopContent); } return content; } }
模板支持单层字段和简单列表绑定。