我正在尝试发送一个带有超链接到 html 电子邮件模板的列表,该列表包含多个项目(文档路径),但我只能在电子邮件中获取一个项目(列表中的第一个项目)。>
asp.net 代码:
private string GetEmailBody(List<string> blob)
{
string strContent = string.Empty;
StringBuilder body = new StringBuilder();
var webRequest = WebRequest.Create(@"https://email template path");
using (var response = webRequest.GetResponse())
using (var content = response.GetResponseStream())
using (var reader = new StreamReader(content))
{
strContent = reader.ReadToEnd();
}
var emailBody = strContent;
body.Append(emailBody);
foreach (var path in blob.ToList())
{
body.Replace("{{Report.Path}}", path.ToString());
}
foreach (var name in fileName.ToList())
{
body.Replace("{{Report.Name}}", name.ToString());
}
return body.ToString();
}
}
blob.ToList 包含路径列表。
fileName.ToList 包含文件名列表。
电子邮件 HTML 模板:
<div align="center">
<p>
<ul>
<li>
<a href="{{Report.Path}}" class="button">{{Report.Name}}</a>
</li>
</ul>
</p>
</div>
我也尝试过使用 *ngFor 但没有成功。
我想显示这样的东西。目前它只显示 1 个报告,我需要列表中的所有报告
[
感谢任何建议/建议和帮助。谢谢
答案 0 :(得分:0)
您的电子邮件模板只有一个 <li>
元素(作为列表项的模板)。您的代码实际上第一次替换了它,并且所有下一次都无法替换(不替换任何内容)。这里需要进行以下步骤:
<ul>
元素<li>
中提取列表项模板,然后删除该 <li>
<li>
元素添加到父 <ul>
。您可以使用一些库来帮助解析和修改一般的 XML 或特定的 HTML,例如 htmlagilitypack
。然而,它只是工具之一,上述步骤是最重要的(要实现的基本逻辑/算法)。这里我介绍一种使用框架内置的System.Xml.Linq
(或Linq-to-xml)的方法。这更方便,但它需要使用严格的 XML 格式。我想您可以确保您的电子邮件模板。
var xdoc = XDocument.Parse(emailBody);
//NOTE: this supposes there is only one <ul>
var ul = xdoc.Descendants().FirstOrDefault(e => e.Name.ToString().ToLower() == "ul")
//the list item template
var li = ul.FirstNode;
//get the actual template
var template = li.CreateNavigator().InnerXml;
//remove the template item, we'll add all later
li.Remove();
//suppose the number of report paths should be equal to the number of filenames
var listItems = blob.Zip(filename, (path,name) => {
var liHtml = template.Replace("{{Report.Path}}", path)
.Replace("{{Report.Name}}", name);
return new XElement("li", XElement.Parse(liHtml));
});
//add the list items to the parent <ul>
foreach(var listItem in listItems){
ul.Add(listItem);
}
//finally return the processed template
return xdoc.ToString();
对于无效的 xml(来自您的电子邮件模板),代码可能会抛出 XmlException
,您可以尝试捕获它并提供有用的异常或消息以发送给客户端。