Create Email Body With Dynamic Table Format In C#

This blog will explain how to create HTML Table with mutiple rows in Email body dynamically using C#.

C# Code
  1. 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>";  
  2.                for (int loopCount = 0; loopCount < data_table.Rows.Count; loopCount++)  
  3.                {  
  4.                    textBody += "<tr><td>" + data_table.Rows[loopCount]["RowName"] + "</td><td> " + data_table.Rows[loopCount]["RowName2"] + "</td> </tr>";  
  5.                }  
  6.                textBody += "</table>";  
  7.                MailMessage mail = new MailMessage();  
  8.                System.Net.Mail.SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");  
  9.   
  10.                mail.From = new MailAddress("From_Email");  
  11.                mail.To.Add("To_Email");  
  12.                mail.Subject = "Test Mail";  
  13.                mail.Body = textBody;  
  14.                mail.IsBodyHtml = true;  
  15.                SmtpServer.Port = 587;  
  16.                SmtpServer.Credentials = new System.Net.NetworkCredential("from_email""from_email_passowrd");  
  17.                SmtpServer.EnableSsl = true;  
  18.   
  19.                SmtpServer.Send(mail);  
Note 
  1. 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.
  1. 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.
  1. for (int loopCount = 0; loopCount < data_table.Rows.Count; loopCount++)    
  2.              {    
  3.                  textBody += "<tr><td>" + data_table.Rows[loopCount]["RowName"] + "</td><td> " + data_table.Rows[loopCount]["RowName2"] + "</td> </tr>";    
  4.              }    
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,
  1. mail.From = new MailAddress("from_email");  
  2.                 mail.To.Add("To_email");  
  3.                 mail.Subject = "Email Subject";  
 Mail.from - Enter from email ID
  
 Mail.To  -  Enter To email ID
 
 Mail.Subject - Subject for email.