How to apped in table format using String builder - c#

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();

Related

How to send a string as MJML with MailKit in ASP.NET core?

I want to send *Account_Name, Account, Date, Type, Income, Expense
Between two dates(startDate and endDate) Via email
SO I built email body like this:
var model = new AllTransactionViewModel();
model = emailAllTransactionsList(startDate, endDate);
MimeMessage message = new MimeMessage();
message.From.Add(new MailboxAddress("karnarthi", "karnarthi.janu#gmail.com"));
message.To.Add(MailboxAddress.Parse("ilajir.janu#gmail.com"));
message.Subject = "Transactions between " + startDate + "and " + endDate;
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = $"<table><tr><th>Account</th><th>Amount</th><th>Date</th><th>Type</th></tr>";
foreach (var item in model.AllTransactions)
{
bodyBuilder.HtmlBody += $"<tr><td>{item.Account_Name}</td><td>{item.Amount}</td><td>{item.Date}</td><td>{item.Type}</td></tr>";
}
foreach (var item in model.IncomeLists)
{
bodyBuilder.HtmlBody += $"<b>Total Income: {item.Income}</b><br>";
}
foreach (var item in model.ExpenseLists)
{
bodyBuilder.HtmlBody += $"<b>Total Expense: {item.Expense}</b><br>";
}
bodyBuilder.TextBody = "This is some plain text";
message.Body = bodyBuilder.ToMessageBody();
I am sending this message like this:
SmtpClient client = new SmtpClient();
try
{
client.Connect("Smtp.gmail.com", 465, true);
client.Authenticate("karnarthi.janu#gmail.com", "<snip>");
client.Send(message);
Console.WriteLine("----- EMAIL SENT!! -----");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
client.Disconnect(true);
client.Dispose();
}
I have sent it succesfully, In the end Email looks like
Now I want to use MJML Framework and make it responsive
so I have changed the email body like this:
var model = new AllTransactionViewModel();
model = emailAllTransactionsList(startDate, endDate);
Console.WriteLine(model.AllTransactions);
MimeMessage message = new MimeMessage();
message.From.Add(new MailboxAddress("santosh kumar", "santosh.metikoti#gmail.com"));
message.To.Add(MailboxAddress.Parse("santoshnani121#gmail.com"));
message.Subject = "Transactions between " + startDate + "and " + endDate;
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = $"\<mjml\>\< mj - body \>\< mj - section \>\< mj - column \>\< mj - table \>\< tr \>\< th \> Account \</ th \>\< th \> Amount \</ th \>\< th \> Date \</ th \>\< th \> Type \</ th \> \</ tr \> \<tr\> ";
foreach (var item in model.AllTransactions)
{
bodyBuilder.HtmlBody += $" \< tr \>\< td \>{item.Account_Name}\</ td \>\< td \> {item.Amount}\</ td \>\< td \>{item.Date}\</ td \>\<td\>{item.Type}\</td\>\</ tr \>";
}
bodyBuilder.HtmlBody += $"\</tr\>\</ mj - table \>\</ mj - column \>\</ mj - section \>\</ mj - body \>\</ mjml \>";
bodyBuilder.TextBody += $"This is some plain text";
message.Body = bodyBuilder.ToMessageBody();
but this EMAIL looks like
Only email email syntax is sending,
How can I send a STYLED EMAIL with MJML wit these Deails
Please Help me With this, I am so Close to doing this

Sending datagridview as mail with header

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;
}

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

C# + Append DataTable row to html email template

I have a DataTable of records which I need to append as information to my Email template htm. Currently what I am doing here works fine but that is if I only have 1 row of record. How can I go about appending the htm template such that I can have multiple postings in the email
e.g Sample Email Screen (Assuming my DataTable returns 3 rows of record):
Dear Sir, your daily car posting results:
Image
Toyota
Cambry
$10000
Image
Honda
GT
$10000
Image
Nissan
Sunny
$10000
Loop DataTable row:
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
primaryImage = dr["PrimaryImage"].ToString();
email = dr["Email"].ToString();
postTitle = dr["Model"].ToString();
model = dr["Model"].ToString();
askingPrice = dr["AskingPrice"].ToString();
var mail = new Email();
mail.IsBodyHtml = true;
mail.MailAddresses = email;
mail.MailSubject = "Test";
mail.HtmFileName = "Email.htm";
var dict = new Dictionary<string, string>
{
{"<%PrimaryImage%>", primaryImage },
{"<%PostTitle%>", postTitle},
{"<%Model%>", model},
{"<%AskingPrice%", askingPrice}
};
mail.Dict = dict;
MailMessage mailMessage;
mailMessage = mail.CreateMailMessage();
Email.Send(mailMessage, 3, 3000, true);
}
}
Create Mail Message:
public MailMessage CreateMailMessage()
{
MailMessage mail = new MailMessage();
mail.IsBodyHtml = IsBodyHtml;
mail.From = new MailAddress("xxx#yahoo.com", "xxx");
mail.Bcc.Add(MailAddresses);
mail.Subject = MailSubject;
string body = "";
string filePath =
HttpContext.Current.Server.MapPath("~/" + ConfigurationManager.AppSettings["TEMPLATES"] + "/");
if (File.Exists(filePath + HtmFileName))
{
FileStream f = new FileStream(filePath + HtmFileName, FileMode.Open);
StreamReader sr = new StreamReader(f);
body = sr.ReadToEnd();
foreach (var pair in Dict)
{
body = body.Replace(pair.Key, pair.Value);
}
f.Close();
}
mail.Body = body;
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess |
DeliveryNotificationOptions.OnFailure;
return mail;
}
Portion of the Email.htm template:
<body>
<form id="form1" runat="server">
<div style="border: thin solid #E1E1E1; background-color: #F0F0F0; margin-bottom: 10px; padding-top: 3px; padding-bottom: 3px; padding-left:5px;">
Postings
</div>
<div>
<a><img src="<%PrimaryImage%>"/></a>
<br/><br/>
Sell Post Title: <%PostTitle%>
<br/><br/>
Model: <%Model%>
<br/><br/>
Asking Price: <%AskingPrice%>
</div>
</form>
</body>
#M.S : There must be some condition on the basis of which you will decide which attribute goes to which td. You can wrap up this logic in some method and generate a class name. Below is a way how you generate a classname on the basis of rownum.
var className="" ;
var rowNum=0;
foreach (var entry in dataTable)
{
className=GetClassName(rowNum)
innerHtml += "<tr>";
innerHtml += "<td class='"+ className +"'>" + entry.PrimaryImage + "</td> ";
innerHtml += "</tr>";
rowNum++;
}
public static string GetClassName(int rowCount)
{
switch (rowCount)
{
case 1:
return "class1";
case 2:
return "class2";
case 3:
return "class3";
default:
return "unassignedClass";
}
}
I have always used HtmlAgilityPack to prepare htmlcontent and achieve things like this.
private string PrepareHtmlContent(List<DataRow> dataTable)
{
var htmlDocument = new HtmlDocument();
var html = EmailTemplates.GetTemplate("yourTemplate");
htmlDocument.LoadHtml(html);
var recordsContainerNode = htmlDocument.GetElementbyId("dataTable");
if (recordsContainerNode != null)
{
var innerHtml = "";
foreach (var entry in dataTable)
{
innerHtml += "<tr>";
innerHtml += "<td>" + entry.PrimaryImage + "</td> ";
innerHtml += "<td>" + entry.Model + "</td> ";
innerHtml += "<td>" + entry.AskingPrice + "</td> ";
innerHtml += "</tr>";
}
recordsContainerNode.InnerHtml = innerHtml;
}
using (var stringWriter = new StringWriter())
{
htmlDocument.Save(stringWriter);
return stringWriter.GetStringBuilder().ToString();
}
}
And your template should be sth like this
<body>
<form id="form1" runat="server">
<div style="border: thin solid #E1E1E1; background-color: #F0F0F0; margin-bottom: 10px; padding-top: 3px; padding-bottom: 3px; padding-left:5px;">
Postings
</div>
<table>
<thead> </thead>
<tbody id="dataTable">
</tbody>
</table>
</form>
</body>

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