我在寫自動電子郵件。它必須每隔X分鐘掃描一次數據庫並用提醒郵件給人們發送電子郵件等。C#創建可用於發送電子郵件的模板
我已準備好所有底層代碼。我現在需要的只是格式化電子郵件。
在C#中是否有預定義的模板系統,所以我可以創建一個具有不同模板和文件夾的文件夾。標籤,如{NAME}
,所以我只是找到這些,並將其替換。
我可以手動打開一個* .txt文件並替換那些特定的標籤等,但有什麼更聰明的?我不想重新發明輪子。
我在寫自動電子郵件。它必須每隔X分鐘掃描一次數據庫並用提醒郵件給人們發送電子郵件等。C#創建可用於發送電子郵件的模板
我已準備好所有底層代碼。我現在需要的只是格式化電子郵件。
在C#中是否有預定義的模板系統,所以我可以創建一個具有不同模板和文件夾的文件夾。標籤,如{NAME}
,所以我只是找到這些,並將其替換。
我可以手動打開一個* .txt文件並替換那些特定的標籤等,但有什麼更聰明的?我不想重新發明輪子。
我想看看使用StringTemplate的:http://www.stringtemplate.org/
You can do it with MVC 3's Razor templates, even in non-web applications。
因特網搜索Razor templates non-web
會出現很多例子。
可以使用nVelocity
string templateDir = HttpContext.Current.Server.MapPath("Templates");
string templateName = "SimpleTemplate.vm";
INVelocityEngine fileEngine =
NVelocityEngineFactory.CreateNVelocityFileEngine(templateDir, true);
IDictionary context = new Hashtable();
context.Add(parameterName , value);
var output = fileEngine.Process(context, templateName);
這不是太困難從頭開始編寫。我寫了這個快速工具來完成你所描述的內容。它在模式{token}
中查找令牌,並用它從NameValueCollection
中檢索的值替換它們。字符串中的令牌對應於集合中的密鑰,該集合中的密鑰將替換爲集合中密鑰的值。
它還具有足夠簡單的額外好處,可以根據需要進行完全自定義。
public static string ReplaceTokens(string value, NameValueCollection tokens)
{
if (tokens == null || tokens.Count == 0 || string.IsNullOrEmpty(value)) return value;
string token = null;
foreach (string key in tokens.Keys)
{
token = "{" + key + "}";
value = value.Replace(token, tokens[key]);
}
return value;
}
用法:
public static bool SendEcard(string fromName, string fromEmail, string toName, string toEmail, string message, string imageUrl)
{
var body = GetEmailBody();
var tokens = new NameValueCollection();
tokens["sitedomain"] = "http://example.com";
tokens["fromname"] = fromName;
tokens["fromemail"] = fromEmail;
tokens["toname"] = toName;
tokens["toemail"] = toEmail;
tokens["message"] = message;
tokens["image"] = imageUrl;
var msg = CreateMailMessage();
msg.Body = StringUtility.ReplaceTokens(body, tokens);
//...send email
}
我會推薦使用StringBuilder,如果你會做很多替換。它會節省內存並且應該執行得更快。 –
我沒有意識到'StringBuilder'有一個'Replace'方法。謝謝! – Jeff
如果您使用ASP.NET 4您可以從畫廊的NuGet下載RazorMail。它允許使用Razor View Engine與MVC http請求的上下文創建電子郵件。
更多詳細信息可通過以下鏈接找到...
我用這個了很多,插上一個正則表達式和一種根據匹配選擇替換值的方法。
/// </summary>
/// <param name="input">The text to perform the replacement upon</param>
/// <param name="pattern">The regex used to perform the match</param>
/// <param name="fnReplace">A delegate that selects the appropriate replacement text</param>
/// <returns>The newly formed text after all replacements are made</returns>
public static string Transform(string input, Regex pattern, Converter<Match, string> fnReplace)
{
int currIx = 0;
StringBuilder sb = new StringBuilder();
foreach (Match match in pattern.Matches(input))
{
sb.Append(input, currIx, match.Index - currIx);
string replace = fnReplace(match);
sb.Append(replace);
currIx = match.Index + match.Length;
}
sb.Append(input, currIx, input.Length - currIx);
return sb.ToString();
}
使用示例
Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("name", "value");
TemplateValues tv = new TemplateValues(values);
Assert.AreEqual("valUE", tv.ApplyValues("$(name:ue=UE)"));
/// <summary>
/// Matches a makefile macro name in text, i.e. "$(field:name=value)" where field is any alpha-numeric + ('_', '-', or '.') text identifier
/// returned from group "field". the "replace" group contains all after the identifier and before the last ')'. "name" and "value" groups
/// match the name/value replacement pairs.
/// </summary>
class TemplateValues
{
static readonly Regex MakefileMacro = new Regex(@"\$\((?<field>[\w-_\.]*)(?<replace>(?:\:(?<name>[^:=\)]+)=(?<value>[^:\)]*))+)?\)");
IDictionary<string,string> _variables;
public TemplateValues(IDictionary<string,string> values)
{ _variables = values; }
public string ApplyValues(string template)
{
return Transform(input, MakefileMacro, ReplaceVariable);
}
private string ReplaceVariable(Match m)
{
string value;
string fld = m.Groups["field"].Value;
if (!_variables.TryGetValue(fld, out value))
{
value = String.Empty;
}
if (value != null && m.Groups["replace"].Success)
{
for (int i = 0; i < m.Groups["replace"].Captures.Count; i++)
{
string replace = m.Groups["name"].Captures[i].Value;
string with = m.Groups["value"].Captures[i].Value;
value = value.Replace(replace, with);
}
}
return value;
}
}
(即使你已經選中一個答案,以供將來參考) - 我得到了我的一個類似性質的問題,一些驚人的答覆:Which approach to templating in C sharp should I take?
String.Replace(「{Name}」,「」)有問題? –
@ csharptest.net一無所有,但一如既往,可能會有更好的事情,隨着我的項目前進,我不會感到驚訝,如果需求稍有改變,這將需要更多的勇氣。 – Luke