This blog will explain how to create HTML Table with mutiple rows in Email body dynamically using C#.
C# Code
- string textBody = " <table border="+1+" cellpadding="+0+" cellspacing="+0+" width = "+400+"><tr bgcolor='#4da6ff'><td><b>Column 1</b></td> <td> <b> Column 2</b> </td></tr>";
- for (int loopCount = 0; loopCount < data_table.Rows.Count; loopCount++)
- {
- textBody += "<tr><td>" + data_table.Rows[loopCount]["RowName"] + "</td><td> " + data_table.Rows[loopCount]["RowName2"] + "</td> </tr>";
- }
- textBody += "</table>";
- MailMessage mail = new MailMessage();
- System.Net.Mail.SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
- mail.From = new MailAddress("From_Email");
- mail.To.Add("To_Email");
- mail.Subject = "Test Mail";
- mail.Body = textBody;
- mail.IsBodyHtml = true;
- SmtpServer.Port = 587;
- SmtpServer.Credentials = new System.Net.NetworkCredential("from_email", "from_email_passowrd");
- SmtpServer.EnableSsl = true;
- SmtpServer.Send(mail);
Note
- mail.IsBodyHtml = true;
IsBodyHTML would enable table view in the email.
We can set the table css within the code as well. Please find the snippet below.
- string textBody = " <table border="+1+" cellpadding="+0+" cellspacing="+0+" width = "+400+"><tr bgcolor='#4da6ff'><td><b>Column 1</b></td> <td> <b> Column 2</b> </td></tr>";
This table has a border, with cellpadding and column background color as well.
For dynamically creating rows in the table for an email, please find the below code snippet for explanation.
For dynamically creating rows in the table for an email, please find the below code snippet for explanation.
- for (int loopCount = 0; loopCount < data_table.Rows.Count; loopCount++)
- {
- textBody += "<tr><td>" + data_table.Rows[loopCount]["RowName"] + "</td><td> " + data_table.Rows[loopCount]["RowName2"] + "</td> </tr>";
- }
We will be looping the data table, with respect to the colum name, it will display in the specific column.
Other settings while sending email code snippet are below,
- mail.From = new MailAddress("from_email");
- mail.To.Add("To_email");
- mail.Subject = "Email Subject";
Mail.from - Enter from email ID
Mail.To - Enter To email ID
Mail.Subject - Subject for email.

Mark ChintisPosted Oct 11, 2021, 9:18 PM
This was a life saver. Thank you very much.
Kalyani GanjiPosted Aug 27, 2020, 11:13 AM
Hi, thank you for this solution but it is not showing the table in the outlook, it is showing string text body content as it is. Can you please help me here.
Kooi MainPosted Mar 17, 2020, 1:32 AM
May i know how to set autofit of table based on body content?
Christian SchmidPosted Jun 26, 2019, 4:50 AM
Hey thanks for this solution, was looking for it. But I don't understand how to add data to the Colum2 in the row. Is this achieved with the "data_table.Rows[loopCount][RowName2]" ?
BHARGAVI DESHPANDEPosted Oct 17, 2018, 9:31 AM
What is data_table.Rows here?