C#+将DataTable行附加到html电子邮件模板

时间:2013-12-01 05:16:34

标签: c# html email

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

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

Dear Sir, your daily car posting results:

Image
Toyota
Cambry
$10000

Image
Honda
GT
$10000

Image
Nissan
Sunny
$10000

循环DataTable行:

 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>

2 个答案:

答案 0 :(得分:2)

@ 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";
    }
}

答案 1 :(得分:0)

我一直使用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>