Sending datagridview as mail with header - c#

This is my code to send datagridview as email. This code works for me by just sending the data in the datagridview.
Please guide me how to add the table header in it. I want the email to be sent as whole table including the table header.
var client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Credentials = new NetworkCredential("from_mail", "password");
var mail = new MailMessage();
mail.From = new MailAddress("from_mail");
mail.To.Add("to_mail");
mail.IsBodyHtml = true;
mail.Subject = "test";
string mailBody = "<table width='100%' style='border:Solid 1px Black;'>";
foreach (DataGridViewRow row in dataGridView2.Rows)
{
mailBody += "<tr>";
foreach (DataGridViewCell cell in row.Cells)
{
mailBody += "<td>" + cell.Value + "</td>";
}
mailBody += "</tr>";
}
mailBody += "</table>";
//your rest of the original code
mail.Body = mailBody;
client.Send(mail);
MessageBox.Show("mail send");
this.Close();

For converting your DataGridView to HTML for sending it in an email, use the function below:
private StringBuilder DataGridtoHTML(DataGridView dg)
{
StringBuilder strB = new StringBuilder();
//create html & table
strB.AppendLine("<html><body><center><" +
"table border='1' cellpadding='0' cellspacing='0'>");
strB.AppendLine("<tr>");
//create table header
for (int i = 0; i < dg.Columns.Count; i++)
{
strB.AppendLine("<td align='center' valign='middle'>" +
dg.Columns[i].HeaderText + "</td>");
}
//Close the header row
strB.AppendLine("</tr>");
//create table body
for (int i = 0; i < dg.Rows.Count; i++)
{
strB.AppendLine("<tr>");
foreach (DataGridViewCell dgvc in dg.Rows[i].Cells)
{
strB.AppendLine("<td align='center' valign='middle'>" +
dgvc.Value.ToString() + "</td>");
}
strB.AppendLine("</tr>");
}
//table footer & end of html file
strB.AppendLine("</table></center></body></html>");
return strB;
}

Related

how to add two tables to the html table in c#

i had a c# code where i was getting a table from sql database and mailing it as html table now i want to send two tables...how can i do that.
what i tried previously:
public static string HtmlTable(DataTable table)
{
try
{
string messageBody = "<font> " + "table value" + " </font><br><br>";
string empty_message = "Null DATA in table value";
if (table.Rows.Count == 0)
{
return empty_message;
}
string htmlTableStart = "<table style=\"border-collapse:collapse; text-align:center;\" >";
string htmlTableEnd = "</table>";
string htmlHeaderRowStart = "<tr style =\"background-color:#6FA1D2; color:#ffffff;\">";
string htmlHeaderRowEnd = "</tr>";
string htmlTrStart = "<tr style =\"color:#555555;\">";
string htmlTrEnd = "</tr>";
string htmlTdStart = "<td style=\" border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px;\">";
string htmlTdEnd = "</td>";
messageBody += htmlTableStart;
messageBody += htmlHeaderRowStart;
foreach (DataColumn column in table.Columns)
messageBody += htmlTdStart + column + htmlTdEnd;
messageBody += htmlHeaderRowEnd;
foreach (DataRow row in table.Rows)
{
messageBody += htmlTrStart;
foreach (var item in row.ItemArray)
{
messageBody += htmlTdStart;
messageBody += item;
messageBody += htmlTdEnd;
}
messageBody += htmlTrEnd;
}
messageBody += htmlTableEnd;
return messageBody;
}
catch (Exception ex)
{
return null;
}
}
the above code only generates one html table but what i need is i will be passing 2 tables. i need two tables to genertaed in my html. i will be passing two tables as arguments.on simple note i need 2 tables to be printed in my html body.
i will be passing two tables or data set which has two tables
public static string HtmlTable(DataTable table,datatable table2)
This could be as simple as including a builder method which will take in a list of DataTable using the seperation of concerns principle and build each table out, returning the end result for you to display to the client.
public static string HtmlTableBuilder(List<DataTable> tables)
{
string tableResponse = "";
foreach (var table in tables)
{
tableResponse += HtmlTable(table);
}
return tableResponse;
}

How to apped in table format using String builder

I am trying to make a table format in the body of email.
This is how I do the appending
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<table border='1' cellpadding='0' cellspacing='0'>");
sb.Append("<tr>");
sb.Append("<td>ID</td>");
sb.Append("<td>STATUS</td>");
sb.Append("</tr>");
//sb.Append("</table>");
//sb.Append(" < table border = '1' cellpadding = '0' cellspacing = '0' width = '100%' >");
foreach (var item in mylist)
{
sb.Append("<tr>");
sb.Append("<td>" + item.message + "</td>");
sb.Append("<td>" + item.transactionid + "</td>");
sb.Append("</tr>");
}
sb.Append("</table>");
var sendmail = new MailAddress("", "Akhil");
var receiver = new MailAddress("", "Buddy");
var subject = "Request for Asset!!";
var body = sb.ToString();
If you using System.Web.Mail then put messageg.BodyFormat = MailFormat.Html;
If you using System.Net.Mail then put message.IsBodyHtml = true; .
IsBodyHtml & MailFormat.Html states that your message is HTML formatted.
> This is not a true way, first you should add the HTML file, then after create a table inside the file.
Now attach a file with StringBuilder.
## Here is my send email with attachment code ##
StringBuilder sbMailBody = new StringBuilder();
sbMailBody.Append(Server.MapPath("~/Content/fielname.html"));
var sendmail = new MailAddress("", "Akhil");
var receiver = new MailAddress("", "Buddy");
var subject = "Request for Asset!!";
var body = sbMailBody.ToString();

HTML generate rowspan in html table string

I have the following code, which adds rowspan to a datatable in an html string, but I want it not to receive as a parameter a datatable, but instead to receive as a parameter an html string in C#.
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Subject");
dt.Columns.Add("Code");
dt.Columns.Add("Test");
dt.Columns.Add("Class");
dt.Rows.Add("Math", "9", "ABC", "D1");
dt.Rows.Add("Math", "9", "ABD", "D2");
dt.Rows.Add("Math", "9", "ABE", "D3");
dt.Rows.Add("Math", "9", "ABF", "D4");
dt.Rows.Add("Science", "91", "ABG", "D1");
dt.Rows.Add("Science", "91", "ABH", "D2");
dt.Rows.Add("Science", "91", "ABI", "D3");
dt.Rows.Add("English", "191", "ABJ", "D1");
Label1.Text = ConvertDataTableToHTML(dt);
}
public static string ConvertDataTableToHTML(DataTable dt)
{
string html = "<table border=1>";
//add header row
html += "<tr>";
for (int i = 0; i < dt.Columns.Count; i++)
{
html += "<td>" + dt.Columns[i].ColumnName + "</td>";
}
html += "</tr>";
//add rows
string sub = "";
for (int i = 0; i < dt.Rows.Count; i++)
{
html += "<tr>";
int count = dt.Select("Subject ='" + dt.Rows[i][0].ToString() + "'").Count();
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j < 2)
{
if (sub != dt.Rows[i][0].ToString())
{
html += "<td rowspan='" + count + "'>" + dt.Rows[i][j].ToString() + "</td>";
}
continue;
}
html += "<td>" + dt.Rows[i][j].ToString() + "</td>";
}
sub = dt.Rows[i][0].ToString();
html += "</tr>";
}
html += "</table>";
return html;
}
This is the result that I hope
There are a few things wrong with the code, and a few ways you can improve your code:
<table border=1> is missing the quotes around the 1. It should be <table border='1'>.
You are missing the <thead> and <tbody> tags around the row tags.
Instead of constantly using +=, use a StringBuilder.
To make your code cleaner, you can change some of your for loops to foreach loops.
Your code should be changed to something like this:
public static string ConvertDataTableToHTML(DataTable dt)
{
StringBuilder builder = new StringBuilder();
//add header row
builder.Append("<table border='1'><thead><tr>");
foreach (DataColumn col in dt.Columns)
{
builder.Append("<td>");
builder.Append(col.ColumnName);
builder.Append("</td>");
}
builder.Append("</tr></thead><tbody>");
//add rows
string sub = "";
...
builder.Append("</tbody></table>");
return builder.ToString();
}
(Just apply the same concepts to the middle code that I removed.)

Trouble with attaching gridview to email in DotNetNuke

I was looking around and found this. It is quite similar to what I want to accomplish the only problem is that when I run the script nothing happens unless I remove the { attachment } line. However, if I remove that line I do not get my attachment.
private void SendEmail()
{
StringBuilder message;
Attachment attachment;
string strOrderType;
if (lblRequestType.Text == "Order Request")
{
strOrderType = "Order Request";
}
else
{
strOrderType = "Return Request";
}
string strName = txtFname.Text + " " + txtLname.Text;
string strOrderNum = lblOrderNum.Text;
string strSubject = "Request:" + strOrderNum + " - " + strName + " " + strOrderType;
StringWriter writer = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
GridView gridView = new GridView();
gridView.DataSource = sdsOrders;
gridView.AutoGenerateColumns = true;
gridView.DataBind();
gridView.HeaderRow.Style.Add("background-color", "#003c74");
gridView.HeaderRow.Style.Add("color", "#ffffff");
for (int i = 0; i < gridView.Rows.Count; i++)
{
GridViewRow row = gridView.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
row.Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.BackColor = System.Drawing.Color.AliceBlue;
}
}
gridView.RenderControl(htmlWriter);
htmlWriter.Close();
System.Text.Encoding theEncoding = System.Text.Encoding.ASCII;
byte[] theByteArray = theEncoding.GetBytes(writer.ToString());
MemoryStream theMemoryStream = new MemoryStream(theByteArray, false);
//Visitor Message
if (txtEmail.Text.Length > 0)
{
message = new StringBuilder();
message.AppendLine("<h4 style=\"font-family: verdana, arial;\">Company Name</h4>");
message.AppendLine("<p style=\"font-size: small; font-family: verdana, arial;\">Dear " + txtFname.Text + ",</p>");
message.AppendLine("<p style=\"font-size: small; font-family: verdana, arial;\">Company Message.</p>");
message.AppendLine("Your Confirmation number is: " + strOrderNum);
attachment = new Attachment(theMemoryStream, strSubject);
Mail.SendMail("Address1#none.net", txtEmail.Text, "", "Address1#none.net",
"Address1#none.net", MailPriority.Normal, "Company Message", MailFormat.Html, Encoding.UTF8, message.ToString(),
new List<Attachment>() { attachment }, null, null, null, null, Host.EnableSMTPSSL);
}
//Internal Message
message = new StringBuilder();
message.AppendLine("<p style=\"font-size: small; font-family: verdana, arial;\">YAY it worked.</p>");
// need to create new reference to attachment, cannot use same reference to send email twice
attachment = new Attachment(theMemoryStream, strSubject);
Mail.SendMail("Address1#none.net", "Address1#none.net", "", "Address1#none.net",
"", MailPriority.Normal, strSubject, MailFormat.Html, Encoding.UTF8, message.ToString(),
new List<Attachment>() { attachment }, null, null, null, null, Host.EnableSMTPSSL);
}
Please tell me where I am going wrong here

how to send the gridview in email with formatting

I am developing an online ordering web application in which I have to email with perches product details to customer. I have maintain all the data in a data table and then generated the grid view pragmatically as follows
public GridView makeGridview(DataTable Dt)
{
GridView GV = new GridView();
GV.DataSource = Dt;
GV.DataBind();
return GV;
}
then adding this grid view to email
body = body.Replace("{Product_Details}", GridViewToHtml(makeGridview(Dt)));
private string GridViewToHtml(GridView gv)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
gv.RenderControl(hw);
return sb.ToString();
}
This is working fine but the problem is then am unable to design it in our predefine format. This mail will be received by the customer of my website, so I need to convert in to our them.
Please guide me how to format in our them.
If there is an another way to do this then I'm open to that as well.
I would suggest you to not trust the GridView as your rendered html, but instead to use your current data-source for that (DataTable):
public GridView CreateHtmlTable(DataTable dt)
{
//Do your HTML work here, like the following:
string tab = "\t";
StringBuilder sb = new StringBuilder();
sb.AppendLine("<html>");
sb.AppendLine(tab + "<body>");
sb.AppendLine(tab + tab + "<table>");
// headers.
sb.Append(tab + tab + tab + "<tr>");
foreach (DataColumn dc in dt.Columns)
{
sb.AppendFormat("<td>{0}</td>", dc.ColumnName);
}
sb.AppendLine("</tr>");
// data rows
foreach (DataRow dr in dt.Rows)
{
sb.Append(tab + tab + tab + "<tr>");
foreach (DataColumn dc in dt.Columns)
{
string cellValue = dr[dc] != null ? dr[dc].ToString() : "";
sb.AppendFormat("<td>{0}</td>", cellValue);
}
sb.AppendLine("</tr>");
}
sb.AppendLine(tab + tab + "</table>");
sb.AppendLine(tab + "</body>");
sb.AppendLine("</html>");
}
Follow follwing code:
public void SendHTMLMail()
{
MailMessage Msg = new MailMessage();
MailAddress fromMail = new MailAddress("administrator#aspdotnet-suresh.com");
// Sender e-mail address.
Msg.From = fromMail;
// Recipient e-mail address.
Msg.To.Add(new MailAddress("suresh#gmail.com"));
// Subject of e-mail
Msg.Subject = "Send Gridivew in EMail";
Msg.Body += "Please check below data <br/><br/>";
Msg.Body += GetGridviewData(gvUserInfo);
Msg.IsBodyHtml = true;
string sSmtpServer = "";
sSmtpServer = "10.2.160.101";
SmtpClient a = new SmtpClient();
a.Host = sSmtpServer;
a.EnableSsl = true;
a.Send(Msg);
}
// This Method is used to render gridview control
public string GetGridviewData(GridView gv)
{
StringBuilder strBuilder = new StringBuilder();
StringWriter strWriter = new StringWriter(strBuilder);
HtmlTextWriter htw = new HtmlTextWriter(strWriter);
gv.RenderControl(htw);
return strBuilder.ToString();
}
Refer below doccument:
http://www.aspdotnet-suresh.com/2012/09/how-to-send-gridview-in-email-body-in.html
Honestly what you have done here (rendering a Web Forms control to an email string) seems like a bit of an unintended trick. Honestly it's not that hard to iterate through a collection and build an HTML table using a StringBuilder.
I believe that for email HTML the convention is often to use inline styles to guarantee the best compatibility with email clients. So you'd want to style your elements like so:
<table>
<tbody>
<tr style="background-color: #EE0000">
<td style="text-transform: uppercase"></td>
...
</tr>
</tbody>
</table>
In the past I've done this by creating an HTML file with everything how I want it and using placeholders like {VariableName} and then doing a string replace on the variables with their values. This way you separate your HTML view from the C# code. It'd be a little tricky with a list of items, in that case you'd have at least two HTML templates: one for the entire document and one for the item rows.
I ran into a similar issue like yours, and I got it done like this:
encapsulated the functionality in a separate HelperClass for ease of use. Used static variables and methods to keep it simple
write the HTML code to format the content of the GridView to a nice table (with zebra stripes and stuffs)
public static StringBuilder gridViewToHTML(GridView gv)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<html>");
sb.AppendLine("<body>");
sb.AppendLine(#"<table style='padding: 10px; font-family: Verdana; font-size:11px;
border-style:solid;border-width:1px;border-color:grey;'> ");
sb.AppendLine("<tr>");
/* *** Build header of the HTML table *** */
for (int i = 0; i < gv.Columns.Count; i++)
{
sb.AppendLine("<td style='font-weight:bold;background-color:black;color:white;'>" + gv.Columns[i].HeaderText + "</td>");
}
sb.AppendLine("</tr>");
/* *** Build body of the HTML table *** */
for (int i = 0; i < gv.Rows.Count; i++)
{
sb.AppendLine("<tr>");
foreach (DataControlFieldCell gvcell in gv.Rows[i].Cells)
{
sb.AppendLine("<td style='text-align;left;'>" + gvcell.ToString() + "</td>");
}
sb.AppendLine("</tr");
}
sb.AppendLine("</table>");
sb.AppendLine("</body>");
sb.AppendLine("</html>");
return sb;
}
send the email message using the StringBuilder object as html formatting of the content, and the casual parameters (to Whom, and Subject)
public static void sendEmailMessage(StringBuilder stringBuilder, string email_ToAddress, string email_Subject)
{
DateTime now = DateTime.Now;
DateTime yesterday = DateTime.Now.AddDays(-1);
MailMessage mail = new MailMessage();
//SomeEmailAccount#yourOrganization.com must be set by your Sysadmin before using it.
mail.From = new MailAddress("SomeEmailAccount#yourOrganization.com");
mail.To.Add(email_ToAddress);
mail.Subject = $"{email_Subject} . Date #{now.ToShortDateString()}";
mail.Body = stringBuilder.ToString();
mail.IsBodyHtml = true;
NetworkCredential autentificare = new NetworkCredential();
autentificare.UserName = "SomeEmailAccount#yourOrganization.com"";
autentificare.Password = "yourPassw0rd";
SmtpClient smtp = new SmtpClient();
smtp.Host = "mail.yourOrganization.com";
smtp.UseDefaultCredentials = true;
smtp.Credentials = autentificare;
smtp.Port = 25;
smtp.EnableSsl = false;
smtp.Send(mail);
}

Categories

Resources