I am having troubles sending email with embedded image. I tried some solutions using word editor but they can't solve my circumstances. I can't use SmtpClient becuase a client does not want it. He has exchange and needs to have sent email in sent folder.
I want send an email in html format with eg. image in header - logo and image in footer - sign.
I have and HTML template stored in database as string to provide more looks and purposes of an email. Specific data I insert using variables which are replaced in moment of sending.
Does anyone know how to add image stored in database to email into without using mailitem.wordeditor and without need to display inspector? Let's assume the images are already on disc or can be a stream somehow used?
My application needs send in background without notify the user by another windows. Adding images using wordeditor needs to have inspector displayed. And even when I immediately close it, it blinks.
The second trouble is how to format HTMLBody property of mailitem, when it does not accept normal HTML but only their so-called html. Is it really needed to study their word html?
Firstly I used MailMessage and this template worked even with images and alternativeviews. Maybe exist some posibility to use MailMessage to send it via outlook, but I dont know it.
Does anoyne came accross with it?
public void SendEmailViaOutlook()
{
//in template I mostly need to use table and css to divide email into blocks - header, content, footer
String htmlTemplate = "<html>\n";
htmlTemplate += " <head>\n";
htmlTemplate += " <style type=\"text//css\">\n";
htmlTemplate += " #Header {border-width: 1; border: solid; text-align: center}\n";
htmlTemplate += " #Content {border-width: 1; border: solid; text-align: center}\n";
htmlTemplate += " #Footer {border-width: 1; border: solid; text-align: center}\n";
htmlTemplate += " </style>\n";
htmlTemplate += " </head>\n";
htmlTemplate += " <body>\n";
htmlTemplate += " <table>\n";
htmlTemplate += " <tr><td><img src=\"cid:companylogo\"/></td></tr>\n";
htmlTemplate += " <tr><td><div id=\"Header\">$HEADER$</div></td></tr>\n";
htmlTemplate += " <tr><td><div id=\"Contentr\">$CONTENT$</div></td></tr>\n";
htmlTemplate += " <tr><td><div id=\"Footer\">$FOOTER$</div></td></tr>\n";
htmlTemplate += " <tr><td><img src=\"cid:usersign\"/></td></tr>\n";
htmlTemplate += " </table>\n";
htmlTemplate += " </body>n";
htmlTemplate += "</html>\n";
//the code is simplified to demostrate problem
//$CONTENT etc. will be replaced by another html from custom html wysiwyg editor
try
{
Outlook.Application outlook = new Outlook.Application();
Outlook._MailItem outLookMailMessage = outlook.CreateItem(Outlook.OlItemType.olMailItem) as Outlook._MailItem;
outLookMailMessage.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
/*
here a I have problem to set the property - my template is not
set and a blank email is sent - almost none html it takes except the example from msdn http://support.microsoft.com/kb/310262, are there some rules how to write it?
*/
outLookMailMessage.HTMLBody = htmlTemplate;
outLookMailMessage.Subject = this.Subject;
outLookMailMessage.Recipients.Add("somenone#somewhere.com");
/*
here I woud need somehow link 2 images with cid companylogo and usersign
*/
outLookMailMessage.Send();
outLookMailMessage = null;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Any help would be much appreciated!
Here is the code for sending the image in oulook
Configuration config = System.Web.Configuration.WebConfigurationManager
.OpenWebConfiguration(HttpContext.Request.ApplicationPath);
var settings = (System.Net.Configuration.MailSettingsSectionGroup)
config.GetSectionGroup("system.net/mailSettings");
var smtp = settings.Smtp;
System.Net.Configuration.SmtpNetworkElement network = smtp.Network;
var outlookApp = new Microsoft.Office.Interop.Outlook.Application();
var mailItem = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);
mailItem.To = network.TargetName;
Attachment attachment = mailItem.Attachments.Add
( "C://test.bmp"
, OlAttachmentType.olEmbeddeditem
, null
, "test image"
);
string imageCid = "test.bmp#123";
attachment.PropertyAccessor.SetProperty
( "http://schemas.microsoft.com/mapi/proptag/0x3712001E"
, imageCid
);
mailItem.BodyFormat = OlBodyFormat.olFormatRichText;
mailItem.HTMLBody = String.Format
( "<body><img src=\"cid:{0}\"></body>"
, imageCid
);
mailItem.Importance = OlImportance.olImportanceNormal;
mailItem.Display(false);
<mailSettings>
<smtp from="test#gmail.com">
<network host="hostname" port="portrnumber"
userName="domain/username" password="password"
targetName="targetname#gmail.com"/>
</smtp>
</mailSettings>
Check this msdn thread on embedding an image
Have you tried using SmtpClient as shown here?
System.Net.Mail.Attachment inline = new System.Net.Mail.Attachment(#"imagepath\filename.png");
inline.ContentDisposition.Inline = true;
public void SendEmailViaOutlook()
{
String htmlTemplate = "<html>\n";
htmlTemplate += " <head>\n";
htmlTemplate += " <style type=\"text//css\">\n";
htmlTemplate += " #Header {border-width: 1; border: solid; text-align: center}\n";
htmlTemplate += " #Content {border-width: 1; border: solid; text-align: center}\n";
htmlTemplate += " #Footer {border-width: 1; border: solid; text-align: center}\n";
htmlTemplate += " </style>\n";
htmlTemplate += " </head>\n";
htmlTemplate += " <body>\n";
htmlTemplate += " <table>\n";
htmlTemplate += " <tr><td><img src=\"cid:companylogo.jpg#embed\"/></td></tr>\n";
htmlTemplate += " <tr><td><div id=\"Header\">$HEADER$</div></td></tr>\n";
htmlTemplate += " <tr><td><div id=\"Contentr\">$CONTENT$</div></td></tr>\n";
htmlTemplate += " <tr><td><div id=\"Footer\">$FOOTER$</div></td></tr>\n";
htmlTemplate += " <tr><td><img src=\"cid:usersign.jpg#embed\"/></td></tr>\n";
htmlTemplate += " </table>\n";
htmlTemplate += " </body>n";
htmlTemplate += "</html>\n";
//the code is simplified to demostrate problem
//$CONTENT etc. will be replaced by another html from custom html wysiwyg editor
try
{
Outlook.Application outlook = new Outlook.Application();
Outlook._MailItem outLookMailMessage = outlook.CreateItem(Outlook.OlItemType.olMailItem) as Outlook._MailItem;
outLookMailMessage.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
outLookMailMessage.HTMLBody = htmlTemplate;
outLookMailMessage.Subject = this.Subject;
outLookMailMessage.Recipients.Add("somenone#somewhere.com");
path = ""; //set some path to folder with images
Outlook.Attachment attachment1 = outLookMailMessage.Attachments.Add(path, Outlook.OlAttachmentType.olEmbeddeditem, null, "");
attachment1.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", "companylogo.jpg#EMBED");
Outlook.Attachment attachment2 = outLookMailMessage.Attachments.Add(path, Outlook.OlAttachmentType.olEmbeddeditem, null, "");
attachment2.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", "usersign.jpg#EMBED");
outLookMailMessage.Send();
outLookMailMessage = null;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Related
I am testing the sending of an email with images using CID tag, I make a desktop application that only runs the mail, the program asked me to also place them in the debug folder of the project apart from the folder where I put them, Now I send it to a windows service but it tells me that
Could not find file 'C:\WINDOWS\system32\ img.png
I already put the image in that folder but it still gives me the same error, the image is type .png, this is my email code
private void SendMAil()
{
string htmlBody = "<!DOCTYPE html>" +
"<html xmlns = 'http://www.w3.org/1999/xhtml'>" +
"<head>" +
"<meta http - equiv = 'Content-Type' content = 'text/html; charset=UTF-8'/>" +
"<title> Demystifying Email Design</title>" +
"<meta name = 'viewport' content = 'width=device-width, initial-scale=1.0'/>" +
"</head>" +
"<body style = 'margin: 0; padding: 0;'>" +
"<table align = 'center' border = '0' cellpadding = '0' cellspacing = '0' width = '900' > " +
"<tr>" +
"<td align='left' bgcolor='#F8F8F8' style='padding: 15px 0 15px 0;border-bottom-width:6px;border-bottom-color:#225100;border-bottom-style:solid;'>" +
" <img src=\"cid:img\"' width='90' height='40'>" +
"</td>" +
"</tr>" +
"<tr>" +
"<td bgcolor = '#ffffff' style='padding:30px 30px 65px 30px'>" +
"HELLO!!!"+
"</td>" +
"</tr>" +
"<tr>" +
"<td bgcolor = '#FFFFFF' align='center' style='padding: 15px 0 15px 0;border-top-width:1px;border-top-color:#FA5300;border-top-style:solid;'>" +
"</td>" +
"</tr>" +
"</table>" +
"</body>" +
"</html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString
(htmlBody, null, MediaTypeNames.Text.Html);
LinkedResource inline = new LinkedResource("img.png", MediaTypeNames.Image.Jpeg);
inline.ContentId = "img";
avHtml.LinkedResources.Add(inline);
Attachment att1 = new Attachment(#"img\img.png");
att1.ContentDisposition.Inline = true;
mail.From = new MailAddress("xx#xx.com");
mail.To.Add("xx#xx.com");
mail.Subject = "Alerta Estado Tags";
mail.Body = inline.ContentId;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient
{
Credentials =
new NetworkCredential("xx#xx.com", "****"),
Host = "smtp.gmail.com",
Port = 000,
EnableSsl = true
};
smtp.Send(mail);
mail.Dispose();
}
Where do I put the images? and What would be the path?
Please review your code, you are using 2 paths for the img.png file, once under without specifying any additional path, which will result in the program trying to search the file under the current working directory (system32 in your case) and once searching inside the img folder (which should also be in your current working directory).
There are other issues in your code example,
you are not associating the avHtml to the email message anywhere.
mail.AlternateViews.Add
where do you initializing the mail object?
But the most important, is how do you execute your program?
I assume you are using the windows command line and dragging the program with its full path, which causes your current working directory to stay under System32 (which is the default directory of CMD when running as Administrator.
Therefore, it looks for img.png and img/img.png under System32
The cid tag is used for resources embedded in the email itself. So you have to add the image as an attachment with a certain code (don't have it at the ready at the moment).
That said: don't use it. It's obsolete and blocked by many email clients. Dump your pictures on a webserver and just link to them.
This is my grid which is dynamic. It is saving customer description against each checkbox. That is, if I mark the checkbox against Individual then it saves Y in my database otherwise N. so Now I just want to show tick on checkboxes that are saved Y in the database. Below is the code for my dynamic grid:
public string getCustomerStateGrid()
{
string html = ""; int Count = 1;
DataTable dt = getDataTableFromQuery(#"select Id,cuscheckbox,CustomerDescription from CustomerState3");
html = "<h2> Customer State </h2><br/><table class=\"display unbreakable\" id=\"tblCustomerDetail\" style=\"width:100%; border-collapse: collapse;\"><thead>";
#region Header
html += "<tr><th height='40' class=\"Greyheader\" style=\"width:5%\">S.No</th>";
html += "<th height='40' class=\"Greyheader\" style=\"width:30%\">Customer Status</th>";
html += "<th height='40' class=\"Greyheader\" style=\"width:15%\">Customer Description</th>";
//html += "<th class=\"Greyheader\" style=\"width:12%\">Action</th>";
html += "</tr></thead>";
#endregion
#region Body
html += "<tbody>";
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
html += "<tr class=\"GreyBorder\" id='tblCustomerDetail_" + dr["Id"].ToString() + "' pkid=\"" + dr["Id"].ToString() + "\" class=\"DataRow\">";
html += "<td class=\"GreyBorder\" style=\"text-align:center !important;\">" + Count + "</td>";
html += "<td class=\"GreyBorder\"><input id='txtcuscheckbox_" + dr["Id"].ToString() + "' type=\"checkbox\" style=\" text-align: right; width:95;\" value='" + dr["cuscheckbox"].ToString() + "' class=\"mediumTextField Customer Status\" /></td>";
html += "<td class=\"GreyBorder\"><input id='txtCustomerDescription_" + dr["Id"].ToString() + "' type=\"textbox\" style=\" text-align: right; width:95;\" value='" + dr["CustomerDescription"].ToString() + "' class=\"mediumTextField Customer Description\" /></td>";
html += "</tr>";
Count++;
}
}
else
{
html += "<tr class=\"GreyBorder\" ><td style=\"text-align:center !important;\" class=\"GreyBorder\" colspan='6'>No Data.</td></tr>";
html += "</tr>";
}
html += "</tbody>";
#endregion
html += "<tfoot><tr class='GreyBorder'>";
html += "<td class='GreyBorder' colspan='2'></td> ";
html += "</tr></tfoot>";
html += "</table><br/>";
return html.ToString();
}
I just want to customize this line of code
html += "<td class=\"GreyBorder\"><input
id='txtcuscheckbox_" + dr["Id"].ToString() + "'
type=\"checkbox\"
style=\" text-align: right; width:95;\" value='" + d
dr["cuscheckbox"].ToString() + "' class=\"mediumTextField
Customer Status\" /></td>";
so that it shows tick on checkbox. Can anyone modify my code to achieve this result? Is there any way we can do using ternary operator?
Well in essence you need:
var isChecked = 'Y';
html += isChecked == 'Y' ? "<input type=\"checkbox\" checked>" : "<input type=\"checkbox\">";
However, you are mixing front-end with back-end logic. Wouldnt it better to create a JSON endpoint that returns the data to the front-end and have the front-end generate the HTML?
EDIT:
To modify the current logic you could replace the line for creating the textbox with something like this:
var isChecked = dr["cuscheckbox"].ToString().ToUpper() == "Y" ? "checked" : string.Empty;
html += $"<td class=\"GreyBorder\"><input id='txtcuscheckbox_{dr["Id"].ToString()}' type=\"checkbox\" style=\" text-align: right; width:95;\" class=\"mediumTextField Customer Status\" {isChecked}/></td>";
I'm creating emails that has to be sent out to technicians. There are about 12 emails (only one will be sent out depending on which printer model was chosen). The emails everything is sending out fine. The only problem I'm having is that the images are not displaying, they are showing as attachments with a .bin extention. I'm using a case statement to send out the emails. Any help on what I'm doing wrong will be greatly appreciated. Thanks.
This is how my code looks like:
In case statement:
string headerPath = Server.MapPath("~\\Images\\EmailImages\\1022_03.png");
LinkedResource img1022_03 = new LinkedResource(headerPath);
img1022_03.ContentId = "1022_03";
string tonerPath = Server.MapPath("~\\Images\\EmailImages\\TonerSignature.png");
LinkedResource TonerSignature = new LinkedResource(tonerPath);
TonerSignature.ContentId = "TonerSignature";
string img1022_11Path = Server.MapPath("~\\Images\\EmailImages\\1022_11.png");
LinkedResource img1022_11 = new LinkedResource(img1022_11Path);
img1022_11.ContentId = "1022_11";
AlternateView avDefault = AlternateView.CreateAlternateViewFromString(SendOMD(), null, MediaTypeNames.Text.Html);
avDefault.LinkedResources.Add(img1022_03);
avDefault.LinkedResources.Add(TonerSignature);
avDefault.LinkedResources.Add(img1022_11);
Mail.AlternateViews.Add(avDefault);
This code is inside a case statement of default. Outside the case I add the smtp details:
System.Configuration.Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration("~/web.config");
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
if (mailSettings != null)
{
int port = mailSettings.Smtp.Network.Port;
string host = mailSettings.Smtp.Network.Host;
string password = mailSettings.Smtp.Network.Password;
string username = mailSettings.Smtp.Network.UserName;
}
SmtpClient SMTP = new SmtpClient();
SMTP.Send(Mail);
This is what my email method looks like:
private string SendOMD()
{
string techType = radTechnicianType.SelectedValue.ToString();
string techString = "";
if (techType == "Field Technician")
techString = "Please send a technician to replace the toner on the above mentioned machine.";
else if (techType == "Onsite technician")
techString = "Please replace the toner on the above mentioned machine.";
else
techString = "Please send a technician to replace the toner on the above mentioned machine.";
StringBuilder stringBuilt = new StringBuilder();
stringBuilt.AppendLine(#"<style type=""text/css"">");
stringBuilt.AppendLine(".divStyle { font-family:Verdana,sans-serif, Arial, Helvetica; font-size:10pt; font-weight: bold; }");
stringBuilt.AppendLine(".par { font-family:Verdana,sans-serif, Arial, Helvetica; font-size:10pt; width:658px; }");
stringBuilt.AppendLine("table { border: 1px solid #000; border-collapse: collapse; font-family:Verdana; font-size:10pt; background-color:#dcdcdc; }");
stringBuilt.AppendLine("table td { border-left: 1px solid #000; font-family:Verdana,sans-serif, Arial, Helvetica; font-size:10pt; background-color:snow; border-bottom: 1px solid #000; padding-left:2px; margin-left:2px; padding-right:5px; margin-right:5px; }");
stringBuilt.AppendLine("table td:first-child { border-left: none; font-family:Verdana,sans-serif, Arial, Helvetica; font-size:10pt; background:#dcdcdc; background-color:#dcdcdc; border-bottom: 1px solid #000; }");
stringBuilt.AppendLine("</style>");
stringBuilt.AppendLine(#"<img alt="" src=""cid:1022_03"" width=""817"" height=""123"" />");
stringBuilt.AppendLine("<br/>");
stringBuilt.AppendLine(#"<p class=""par"">Dear " + txtClient.Text.Trim() + ",</p>");
stringBuilt.AppendLine("Details:");
stringBuilt.AppendLine("<br/>");
stringBuilt.AppendLine("<table>");
stringBuilt.AppendLine(#"<tr><td style=""background-color:#dcdcdc; widht:350px;"" >Model: </td><td style=""widht:250px;""> " + lstModelType.SelectedValue.ToString() + " </td></tr>");
stringBuilt.AppendLine(#"<tr><td style=""background-color:#dcdcdc; widht:350px;"" >Serial No: </td><td style=""widht:250px;""> " + txtSerial.Text.Trim() + " </td></tr>");
stringBuilt.AppendLine(#"<tr><td style=""background-color:#dcdcdc; widht:350px;"" >IP Address: </td><td style=""widht:250px;""> " + txtIPAddress.Text.Trim() + " </td></tr>");
stringBuilt.AppendLine(#"<tr><td style=""background-color:#dcdcdc; widht:350px;"" >AD Sharename: </td><td style=""widht:250px;""> " + txtADSharename.Text.Trim() + " </td></tr>");
stringBuilt.AppendLine(#"<tr><td style=""background-color:#dcdcdc; widht:350px;"">Department: </td><td style=""widht:250px;""> " + txtDepartment.Text.Trim() + " </td></tr>");
stringBuilt.AppendLine(#"<tr><td style=""background-color:#dcdcdc; widht:350px;"">Colour: </td><td style=""widht:250px;""> " + lstColour.SelectedValue.ToString() + " </td></tr>");
stringBuilt.AppendLine("</table>");
stringBuilt.AppendLine(#"<p class=""par""><em>" + techString + "</em></p>");
stringBuilt.AppendLine("<br/>");
stringBuilt.AppendLine(#"<div class=""divStyle""> Regards, ");
stringBuilt.AppendLine("<br/>");
stringBuilt.AppendLine(lstApprover.SelectedValue.ToString());
stringBuilt.AppendLine("</div>");
stringBuilt.AppendLine(#"<img alt="" src=""cid:TonerSignature"" width=""300"" height=""70"" />");
stringBuilt.AppendLine("<br/>");
stringBuilt.AppendLine(#"<img alt="" src=""1022_11"" width=""815"" height=""54"" />");
return stringBuilt.ToString();
}
You need to Add mime type to your resources.
for ex : LinkedResource img1022_11 = new LinkedResource(img1022_11Path,MediaTypeNames.Image.Gif);
you can add Jpg, Tiff, Gif images, for png files there is a workaround.
use this.
htmlView.LinkedResources.Add(
new LinkedResource("../EmailTemplate/ContactDetails.png")
{
ContentId = "ContactDetails",
TransferEncoding = TransferEncoding.Base64,
ContentType = new ContentType("image/png")
});
instead of Server.MapPath use website path to get the images
I am implementing an app, which send email to employees in company. That email contains a hyperlink which direct to a pdf file on a shared server folder.
Example url of server folder:
\\server_name\folder_parent\folder_child\file.pdf
In my C# code, I use a string to contain html code like this code below
private static string getHTML(DataTable dt) {
string myBuilder = "";
myBuilder += "<table id='customers' style='font-family: 'Trebuchet MS', Arial, Helvetica, sans-serif; width: 100%; border-collapse: collapse;'";
myBuilder += "<tr>";
foreach (DataColumn myColumn in dt.Columns)
{
myBuilder += "<th style='font-size: 1.1em; border: 1px solid #98bf21; padding: 5px 7px 4px 7px;background-color: #A7C942;'>";
myBuilder += myColumn.ColumnName;
myBuilder += "</th>";
}
myBuilder += "</tr>";
int count = 0;
foreach (DataRow myRow in dt.Rows)
{
myBuilder += "<tr>";
if (count % 2 == 0)
{
foreach (DataColumn myColumn in dt.Columns)
{
myBuilder += "<td style='font-size: 1em; border: 1px solid #98bf21; padding: 3px 7px 2px 7px;'>";
if (myColumn.ColumnName == "Address")
{
myBuilder += "<a href='" + myRow[myColumn.ColumnName].ToString() + "' style='display:block;'>Link!</a>";
}
else
{
myBuilder += myRow[myColumn.ColumnName].ToString();
}
myBuilder += "</td>";
}
}
else
{
foreach (DataColumn myColumn in dt.Columns)
{
myBuilder += "<td style='font-size: 1em; border: 1px solid #98bf21; padding: 3px 7px 2px 7px; color: #000000; background-color: #EAF2D3;'>";
if (myColumn.ColumnName == "Address")
{
myBuilder += "<a href='" + myRow[myColumn.ColumnName].ToString() + "' style='display:block;'>Link!</a>";
}
else
{
myBuilder += myRow[myColumn.ColumnName].ToString();
}
myBuilder += "</td>";
}
}
count++;
myBuilder += "</tr>";
}
myBuilder += "</table>";
return myBuilder;
}
This code gets data from a DataTable and shows it like a table in html code.
This is data for DataTable
dt.Rows.Add("bala", "24", "http://www.google.com", "999444444");
dt.Rows.Add("chendur", "23", "http://www.facebook.com", "9999999999");
dt.Rows.Add("chchandru", "22", #"file:///\\server_name\folderA\folderB\file.pdf", "888888888");
So when I open email on chrome (mail.google.com), the link contains local link didn't work and there was no hyperlink in that text.
I tried with http link like google or facebook and that worked but file link didn't as you can see from this image below.
About the file:///, I tried to write an html file and that worked.
<td>LINK</td>
I have read many articles about this and they say "security problems".
The thing is this app only send email between employees in the same company and they use a shared server for using internet and sending email. (All computers in company connect to a same server).
So is there any possible way to send local link like this situation? If it doesn't, is there any possible solution for me to fix this situation? The requirement is just "You click a link in your email and it's automatically open a file on a local link."
p/s: Of course I got this
MailMessage completeMessage = new MailMessage(From, To, Subject, mailBody);
completeMessage.IsBodyHtml = true;
I know this is an old tread, but I had the same problem..
Instead of sending address as a link I am sending network location inside opening and closing chevron, this way outlook takes it as a whole link. details
So we have intranet application, which send network file location to employees, and all employees uses outlook. I am sending file location like yours
\\server_name\folder_parent\folder_child\file.pdf
with below code:
myBuilder += #"<\\server_name\folder_parent\folder_child\file.pdf>";
PS: my MailMessage instance has utf8 encoding.
mail.BodyEncoding = Encoding.UTF8;
When Im trying to generate HTML Formatted Result set and sending the resultset as Email using SMTPsettings,Its working fine in Outlook but the same htmlformat is not displayed in gmail It displays as a plain Text.
public void GenerateRpt()
{
DataSet ds= new DataSet();
//Result set is assigned to the dataset object.
if ds[0].Rows.Count == 0)
return;
else
{
try
{
StringBuilder builder = new StringBuilder();
builder.Append("<html xmlns='http://www.w3.org/1999/xhtml'>");
builder.Append("<head>");
builder.Append("<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />");
builder.Append(" <style type='text/css'> #page {} table { border-collapse: collapse;border-spacing: 0;empty-cells: show} ");
builder.Append(" .Default { font-family: Calibri;background-color: transparent;border-style: none;vertical-align: bottom;margin-left: 0in;");
builder.Append(" writing-mode: page;color: #000000;font-size: 11pt; font-style: normal;text-shadow: none; text-decoration: none ! important;font-weight: normal;}");
builder.Append(" .ce2 { background-color: #95b3d7;border-width: 0.0349cm;border-style: solid;border-color: #000000;color: #000000;font-size: 11pt;");
builder.Append("font-style: normal;font-weight: bold;margin-left: 0in;text-shadow: none;font-family: Calibri;text-decoration: none ! important;");
builder.Append("vertical-align: middle;writing-mode: page;text-align: center ! important;}");
builder.Append(" .ce5 { background-color: transparent;border-width: 0.0349cm;border-style: solid;border-color: #000000;color: #000000;font-size: 11pt;");
builder.Append("font-style: normal;font-weight: normal;margin-left: 0in;text-shadow: none;font-family: Calibri;text-decoration: none ! important;");
builder.Append("vertical-align: middle;writing-mode: page;text-align: center ! important;}");
builder.Append(" .ce6 { background-color: #a6a6a6;border-width: 0.0349cm;border-style: solid;border-color: #000000;color: #000000;font-size: 11pt;");
builder.Append("font-style: normal;font-weight: bold;margin-left: 0in;text-shadow: none;font-family: Calibri;text-decoration: none ! important;");
builder.Append("vertical-align: middle;writing-mode: page;text-align: center ! important;}");
builder.Append(" .ce13 { background-color: transparent;border-width: 0.0349cm;border-style: solid;border-color: #000000;color: #000000;font-size: 11pt;");
builder.Append("font-style: normal;font-weight: normal;margin-left: 0in;text-shadow: none;font-family: Calibri;text-decoration: none ! important;");
builder.Append("vertical-align: bottom;writing-mode: page;}");
builder.Append(" .contentText {font-size: 11pt;font-weight: normal;font-style: normal;font-style: Calibri;font-weight: bold;COLOR: #cccccc;");
builder.Append("</style>");
builder.Append("</head>");
builder.Append("<body>");
builder.Append("<table border='0' cellpadding='1' cellspacing='1' width='70%'> ");
builder.Append("<tr class='ro1'><td colspan='4'><b><p>RPT NAME</p></b></td></tr>");
builder.Append("<tr class='ro1'>");
builder.Append("<td class='ce2'><p>COL1</p></td>");
builder.Append("<td class='ce2'><p>COL2</p></td>");
builder.Append("<td class='ce2'><p>COL3</p></td>");
builder.Append("<td class='ce2'><p>COL4</p></td>");
builder.Append("</tr>");
string tempdrow = string.Empty;
int i;
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
builder.Append("<td class='ce5'>");
builder.Append("<p>" + ds.Tables[0].Rows[i]["Col1"].ToString() + "</p>");
builder.Append("</td>");
builder.Append("<td class='ce13' style='text-align: center'>");
builder.Append("<p>" + ds.Tables[0].Rows[i]["Col2"].ToString() + "</p>");
builder.Append("</td>");
builder.Append("<td class='ce13' style='text-align: center'>");
builder.Append("<p>" + ds.Tables[0].Rows[i]["Col3"].ToString() + "</p>");
builder.Append("</td>");
builder.Append("<td class='ce13' style='text-align: center'>");
builder.Append("<p>" + ds.Tables[0].Rows[i]["Col4"].ToString() + "</p>");
builder.Append("</td>");
builder.Append("</tr>");
}
// When No more records in the Dataset show the Grand Total.
builder.Append("<tr class='ro2'>");
builder.Append("<td class='ce13' style='text-align: center'>");
builder.Append("<b><p>GRAND TOTAL </p></b>");
builder.Append("</td>");
builder.Append("<td class='ce13' style='text-align: center'>");
builder.Append("<p>" + ds.Tables[0].Rows[i - 1]["Col2"].ToString() + "</p>");
builder.Append("</td>");
builder.Append("<td class='ce13' style='text-align: center'>");
builder.Append("<p>" + ds.Tables[0].Rows[i - 1]["Col3"].ToString() + "</p>");
builder.Append("</td>");
builder.Append("<td class='ce13' style='text-align: center'>");
builder.Append("<p>" + ds.Tables[0].Rows[i - 1]["Col4"].ToString() + "</p>");
builder.Append("</td>");
builder.Append("</tr>");
builder.Append("</table>");
string sVehRejsubject = System.Configuration.ConfigurationManager.AppSettings["Subject"].ToString();
sendmail(builder.ToString(), sVehRejsubject);
}
catch (Exception ex)
{
ex.Message();
}
}
}
// Mail Sending Part
void sendmail(string strResultSet,string strRptType)
{
try
{
if (strResultSet.ToString() != "")
{
string strMessage1 = string.Empty, TestEmp = "Mani";
strMessage1 = strResultSet.ToString();
strMessage1 += "<br><br><font color='blue'><b>Date:</b></font> " + DateTime.Now.ToString("dd/MM/yyyy") + "<BR>";
strMessage1 += "<br>Regards,<BR><BR>";
strMessage1 += TestEmp + "</b><br>";
<BR></td></tr></table></body></html>";
MailMessage mail = new MailMessage();
//SMTP SETTINGS DEFINED IN APP.CONFIG FILE
System.Net.Mail.SmtpClient _client = new System.Net.Mail.SmtpClient();
string sFrom = System.Configuration.ConfigurationManager.AppSettings["emailFrom"].ToString();
string sTo = System.Configuration.ConfigurationManager.AppSettings["emailTo"].ToString();
string sCC = System.Configuration.ConfigurationManager.AppSettings["emailCC"].ToString();
string sBCC = System.Configuration.ConfigurationManager.AppSettings["emailBCC"].ToString();
string sDisplayName = System.Configuration.ConfigurationManager.AppSettings["emailFromDisplayName"].ToString();
mail.From = new MailAddress(sFrom, sDisplayName);
mail.To.Add(new MailAddress(sTo));
if (sCC.ToString() != "")
{
mail.CC.Add(sCC);
}
if (sBCC.ToString() != "")
{
mail.Bcc.Add(sBCC);
}
mail.IsBodyHtml = true;
mail.Subject = strRptType + " AS ON - " + System.DateTime.Now.ToString("dd/MM/yyyy");
mail.Body = strMessage1;
_client.Send(mail);
}
}
catch (Exception ex)
{
Ex.Message();
return;
}
}
Email providers, does not allow the entire spectrum of html tags to be included in a message. In case you try to include an unsupported tag it will be ignored or automatically changed to another tag.
It is the same with unsupported css attributes.
For example <br/> is not allowed and will be ignored
What you should do is use universally supported Html tags only.
I've found this page which lists the universally supported html tags and css attributes
Good luck !