【问题标题】:C# + Append DataTable row to html email templateC# + 将 DataTable 行附加到 html 电子邮件模板
【发布时间】:2013-12-17 00:29:56
【问题描述】:

我有一个记录数据表,我需要将其作为信息附加到我的电子邮件模板 htm。目前我在这里所做的工作正常,但如果我只有 1 行记录的话。我如何才能附加 htm 模板,以便我可以在电子邮件中发布多个帖子

例如电子邮件屏幕示例(假设我的 DataTable 返回 3 行记录)

Dear Sir, your daily car posting results:

Image
Toyota
Cambry
$10000

Image
Honda
GT
$10000

Image
Nissan
Sunny
$10000

循环数据表行:

 for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow dr = dt.Rows[i];

                    primaryImage = dr["PrimaryImage"].ToString();
                    email = dr["Email"].ToString();
                    postTitle = dr["Model"].ToString();
                    model = dr["Model"].ToString();
                    askingPrice = dr["AskingPrice"].ToString();

                    var mail = new Email();
                    mail.IsBodyHtml = true;
                    mail.MailAddresses = email;
                    mail.MailSubject = "Test";

                    mail.HtmFileName = "Email.htm";
                    var dict = new Dictionary<string, string>
                                   {
                                       {"<%PrimaryImage%>", primaryImage },
                                       {"<%PostTitle%>", postTitle},
                                       {"<%Model%>", model},
                                       {"<%AskingPrice%", askingPrice}
                                   };
                    mail.Dict = dict;

                    MailMessage mailMessage;
                    mailMessage = mail.CreateMailMessage();
                    Email.Send(mailMessage, 3, 3000, true);
                    }
                }

创建邮件消息:

public MailMessage CreateMailMessage()
        {
            MailMessage mail = new MailMessage();
            mail.IsBodyHtml = IsBodyHtml;
            mail.From = new MailAddress("xxx@yahoo.com", "xxx");
            mail.Bcc.Add(MailAddresses);
            mail.Subject = MailSubject;
            string body = "";
            string filePath =
               HttpContext.Current.Server.MapPath("~/" + ConfigurationManager.AppSettings["TEMPLATES"] + "/");

            if (File.Exists(filePath + HtmFileName))
            {
                FileStream f = new FileStream(filePath + HtmFileName, FileMode.Open);
                StreamReader sr = new StreamReader(f);
                body = sr.ReadToEnd();
                foreach (var pair in Dict)
                {
                    body = body.Replace(pair.Key, pair.Value);
                }
                f.Close();
            }

            mail.Body = body;
            mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess |
                                               DeliveryNotificationOptions.OnFailure;
            return mail;
        }

Email.htm 模板部分:

<body>
    <form id="form1" runat="server">
        <div style="border: thin solid #E1E1E1; background-color: #F0F0F0; margin-bottom: 10px; padding-top: 3px; padding-bottom: 3px; padding-left:5px;">
            Postings
        </div>
        <div>
             <a><img src="<%PrimaryImage%>"/></a> 
            <br/><br/>
             Sell Post Title: <%PostTitle%>
            <br/><br/>
            Model: <%Model%>
            <br/><br/>
            Asking Price: <%AskingPrice%>
        </div>
    </form>
</body>

【问题讨论】:

    标签: c# html email


    【解决方案1】:

    @M.S :必须有一些条件,您将根据这些条件决定哪个属性转到哪个 td。您可以将此逻辑包装在某个方法中并生成一个类名。下面是一种基于 rownum 生成类名的方法。

    var className="" ;
    var rowNum=0;       
    foreach (var entry in dataTable)
        {
            className=GetClassName(rowNum)
            innerHtml += "<tr>";
            innerHtml += "<td class='"+ className +"'>" + entry.PrimaryImage + "</td> ";
            innerHtml += "</tr>";
            rowNum++;
        }
    
    public static string GetClassName(int rowCount)
    {
        switch (rowCount)
        {
            case 1:
                return "class1";
            case 2:
                return "class2";
            case 3:
                return "class3";
            default:
                return "unassignedClass";
        }
    }
    

    【讨论】:

    • 谢谢@Sameer。让我知道如何解决它。伟大的!!会试试这个。
    【解决方案2】:

    我一直用HtmlAgilityPack来准备htmlcontent,实现这样的东西。

     private string PrepareHtmlContent(List<DataRow> dataTable)
        {
    
            var htmlDocument = new HtmlDocument();
            var html = EmailTemplates.GetTemplate("yourTemplate");
            htmlDocument.LoadHtml(html);
            var recordsContainerNode = htmlDocument.GetElementbyId("dataTable");
    
            if (recordsContainerNode != null)
            {
                var innerHtml = "";
    
                foreach (var entry in dataTable)
                {
    
                    innerHtml += "<tr>";
    
                    innerHtml += "<td>" + entry.PrimaryImage + "</td> ";
                    innerHtml += "<td>" + entry.Model + "</td> ";
                    innerHtml += "<td>" + entry.AskingPrice + "</td> ";
                    innerHtml += "</tr>";
                }
    
    
                recordsContainerNode.InnerHtml = innerHtml;
            }
    
         using (var stringWriter = new StringWriter())
            {
                htmlDocument.Save(stringWriter);
                return stringWriter.GetStringBuilder().ToString();
            }
     }
    

    你的模板应该是这样的

    <body> <form id="form1" runat="server"> <div style="border: thin solid #E1E1E1; background-color: #F0F0F0; margin-bottom: 10px; padding-top: 3px; padding-bottom: 3px; padding-left:5px;"> Postings </div> <table> <thead> </thead> <tbody id="dataTable"> </tbody> </table> </form> </body>

    【讨论】:

    • 你能告诉我如何为两个不同的 添加属性吗?
    • 你是怎么添加td的?添加属性的一种方法是在 HtmlNode 对象 node.SetAttributeValue("style", value) 上使用 SetAttribute 方法
    • 我正在使用您给出的示例。在foreach中向innerHtml添加3 td。但我对每个 td 都有单独的属性。现在我将作为字符串放入 td 本身。比如 "" 。还有其他有效的方法吗?
    • 你如何定义哪个属性去哪个td?你能把你的代码发给我吗?
    • 我仅将您的代码与 innerHtml += "" + entry.PrimaryImage + 一起使用"";我不知道如何为每个 td 定义不同的属性。这就是我需要你的帮助。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签