I want to send mail from asp.net web forms. The problem is that it doesn't fetch the data from backend to show it in the mail

34 Views Asked by At

I want to populate json data on my html email. I don't know the reason why the table is not displayed in the mail.

.cs code:

StringBuilder emailBody = new StringBuilder(); string templatePath = HttpContext.Current.Server.MapPath("~/Mail_Template/AppEmail.html"); string emailTemplate = File.ReadAllText(templatePath); StringBuilder tableRows = new StringBuilder(); foreach (var item in jsonData) { emailBody.AppendLine("<tr>"); emailBody.AppendLine($"<td>{item.App_name}</td>"); emailBody.AppendLine($"<td>{item.From_date}</td>"); emailBody.AppendLine($"<td>{item.To_date}</td>"); emailBody.AppendLine("</tr>"); } string emailBodytoSend = templatePath.Replace("{APPLICATION_ROWS}", tableRows.ToString()); mailMessage.Body = emailBodytoSend.ToString(); mailMessage.Body = emailTemplate; mailMessage.IsBodyHtml = true; smtpClient.Send(mailMessage); }

Html template:

<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <table width="100%" cellspacing="0" cellpadding="0"> <tr> <td align="center"> <h1>Your Email Title</h1> <p>Hello,</p> <p>This is a sample email template for Application Details.</p> <!-- You can include dynamic data here --> <!--<p>Application Name: {APPLICATION_NAME}</p> <p>From Date: {FROM_DATE}</p> <p>To Date: {TO_DATE}</p>--> <table border="1" cellpadding="10"> <tr> <th>Application Name</th> <th>From Date</th> <th>To Date</th> </tr> {APPLICATION_ROWS} </table> <p>You can track the same.</p> <p>Best regards,</p> <p>Your Name</p> </td> </tr> </table> </body> </html>

1

There are 1 best solutions below

0
D A On

Change your code like this:

                string templatePath = HttpContext.Current.Server.MapPath("~/Mail_Template/AppEmail.html");
                string emailTemplate = File.ReadAllText(templatePath);
                StringBuilder tableRows = new StringBuilder();
                foreach (var item in jsonData) {
                    StringBuilder tr = new StringBuilder();
                    tr.AppendLine("<tr>");
                    tr.AppendLine($"<td>{item.App_name}</td>");
                    tr.AppendLine($"<td>{item.From_date}</td>");
                    tr.AppendLine($"<td>{item.To_date}</td>");
                    tr.AppendLine("</tr>");
                    tableRows.Append(tr.ToString());
                }
                string emailBodytoSend = templatePath.Replace("{APPLICATION_ROWS}", tableRows.ToString()); 
                mailMessage.Body = emailBodytoSend.ToString();
                mailMessage.Body = emailTemplate; 
                mailMessage.IsBodyHtml = true; 
                smtpClient.Send(mailMessage);

The problem was that you didn't add the tr data into tableRows variable.