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
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 (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.