Images not displaying in email (shows as .bin) - c#

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

Related

While Sending HTML SVG image code not showing/preview image in Gmail

enter image description hereAdding SVG image code in html code and add html in htmlbody after that sending email so image is not showing
here is my code
---- code ---
MimeMessage emailMessage = new MimeMessage();
MailboxAddress emailFrom = new MailboxAddress("Vcare", "info#ehr-testingdev.signupdemo.com");
emailMessage.From.Add(emailFrom);
MailboxAddress emailTo = new MailboxAddress(emailData.EmailToName, emailData.EmailToId);
emailMessage.To.Add(emailTo);
emailMessage.Subject = emailData.EmailSubject;
BodyBuilder emailBodyBuilder = new BodyBuilder();
var htmlData = #"<table cellpadding='0' cellspacing='0' width='650' style='background - color:#f5f5f5;margin:0 auto;color:#666465;min-width:650px'>"+
"<tbody><tr style='background-color:#00a8da; height:61px'>"+
"<td style='vertical-align:middle'>"+
"<table width ='100%' cellpadding='0' cellspacing='0' height='60'><tbody><tr><td style='width:5%'></td>"+
"<td style ='color:#fff;width:72%;font-size:14px;letter-spacing:1px'><b style='font-size: 17px;'> New Account Details</b></td><td align='right'>"+
" ##Date "+
"" +
"<svg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='100%' viewBox='0 0 698 180' enable - background='new 0 0 698 180' xml: space='preserve'>"+
""+
""+
""+
""+
""+
""+
""+
""+
""+
""+
""+
""+
""+
""+
""+
"" +
"" +
" Dear ##UserFirstName," +
"Congratulations on opening your account successfully at VCare(EHR).Your account is now active and you may login from our home page."+
"Within the members area you can submit and review your listings, view detailed statistics, edit your account details and much more. "+
" Login Details:Email:##userName"+
" Password:</ b > ##userPassword"+
" http://ehr-testingdev.signupdemo.com/"+
"Should you require any help related to your account then do not hesitate to contact us."+
"RegardsSupport Team"+
""+
""+
"<td width='22%' style='color: #fff;line-height:22px;vertical-align:middle;font-family:Open Sans,sans-serif'> Let's Connect!</td>"+
"<td width='100%' style='vertical-align:middle; padding-left: 385px;'>"+
"<a style='' href='http://twitter.com' target='_blank' alt='Twitter' class='CToWUd'> <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 48 48' width='48px' height='48px'><path fill='#3F51B5' d='M42,37c0,2.762-2.238,5-5,5H11c-2.761,0-5-2.238-5-5V11c0-2.762,2.239-5,5-5h26c2.762,0,5,2.238,5,5V37z'/><path fill='#FFF' d='M34.368,25H31v13h-5V25h-3v-4h3v-2.41c0.002-3.508,1.459-5.59,5.592-5.59H35v4h-2.287C31.104,17,31,17.6,31,18.723V21h4L34.368,25z'/></svg> </a>" +
"</td>" +
"<td width='10%' style='vertical-align:middle; display: flex; justify-content: center;'>"+
"<a style='margin-left: 0px;' href='https://www.facebook.com' target='_blank' alt='Facebook' class='CToWUd'> <svg xmlns='http://www.w3.org/2000/svg' width='655.359' height='655.359' fill-rule='evenodd' clip-rule='evenodd' image-rendering='optimizeQuality' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' viewBox='0 0 6.827 6.827'><rect width='6.827' height='6.827' fill='#0a93e2' rx='1.456' ry='1.456'/><path fill='#fff' d='M5.49009 2.3776c-0.147055,0.065189 -0.305406,0.109406 -0.47126,0.129142 0.169453,-0.101665 0.299421,-0.262402 0.361008,-0.453976 -0.158654,0.0938819 -0.334398,0.16228 -0.521224,0.199079 -0.149701,-0.159587 -0.363071,-0.259126 -0.599165,-0.259126 -0.45337,0 -0.820579,0.367598 -0.820579,0.820579 0,0.0642559 0.00711024,0.127079 0.021185,0.187126 -0.681961,-0.0343504 -1.28679,-0.361028 -1.69143,-0.857681 -0.0708268,0.121335 -0.111138,0.262335 -0.111138,0.412661 0,0.284827 0.144882,0.536122 0.364846,0.683177 -0.1345,-0.00420866 -0.260886,-0.041248 -0.371744,-0.102835 0,0.00359843 0,0.0068937 0,0.0104961 0,0.397437 0.28298,0.72915 0.658323,0.804508 -0.0687008,0.0188228 -0.141303,0.0289921 -0.216055,0.0289921 -0.0528504,0 -0.104268,-0.00511811 -0.154535,-0.0146811 0.104657,0.326051 0.407697,0.563295 0.766882,0.569866 -0.280921,0.220244 -0.634752,0.351142 -1.01935,0.351142 -0.0664016,0 -0.131807,-0.00357874 -0.19576,-0.0113228 0.363091,0.232799 0.794343,0.368748 1.2578,0.368748 1.5095,0 2.3352,-1.25067 2.3352,-2.33511 0,-0.035563 -0.000909449,-0.0708465 -0.00236614,-0.10611 0.160413,-0.115673 0.299421,-0.260276 0.40937,-0.424677z'/></svg></a>" +
"</td>" +
"<td width ='50%'></td>"+
"</tr></td></tr></tbody></table></td></tr></tbody ></table> ";
var email = #"##userName";
var pass = #"##userPassword";
var userFirstName = #"##UserFirstName";
var dateTime = DateTime.Now.ToString("dd MMM , yyyy");
var emailHtmlData = htmlData.Replace(email.ToString(), emailData.EmailToId);
var emailHtmlData1 = emailHtmlData.Replace(pass.ToString(), emailData.EmailToPassword);
var emailHtmlData2 = emailHtmlData1.Replace(userFirstName.ToString(), emailData.EmailToName).Replace(#"##Date",dateTime);
//str.Close();
emailBodyBuilder.HtmlBody = emailHtmlData2;
// emailBodyBuilder.TextBody = MailText;// emailData.EmailBody;
emailMessage.Body = emailBodyBuilder.ToMessageBody();
SmtpClient emailClient = new SmtpClient();
emailClient.Connect("smtp.hostinger.com", 465, true);
emailClient.Authenticate("test#gmail.com", "1234");
emailClient.Send(emailMessage);
emailClient.Disconnect(true);
emailClient.Dispose();
It's very difficult to work out your problem here, but, SVGs are not well supported in email. https://www.caniemail.com/features/image-svg/
You should embed the image via an img tag:
<img src="https://www.path.com/to/image.png" width="x" height="y" alt="xyz" />
The image should be uploaded to a publicly available location.

XMLWorker: Invalid nested tag div found, expected closing tag img

I am just trying to add an image to my pdf document using XMLWorker. but for some reason its wanting a close img tag. but even when i put one in it still fails.
C# CODE
Byte[] bytes;
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4.Rotate()))
{
using (var writer = PdfWriter.GetInstance(doc, ms))
{
//Open the document for writing
doc.Open();
//Our HTML and CSS
string exampleHtml = #"<div style='position: relative; width: 100%'>" +
"<img src='/Content/images/certificate.jpg'><img>" +
"<div style='position: absolute; top: 100px; left: 100px; width: 800px; height: 550px; text-align: center;'>" +
"<h1>" +
"<img src='/Content/images/CertTitle.png' alt='CERTIFICATE PDF' style='width: 800px;'/>" +
"</h1>" +
"<p>" +
"The School certifies that<br/>" +
"<h2>FIRSTNAME LAST NAME TITLE</h2>" +
"has participated in the class titled<br />" +
"<h2>COURSCODE - COURSENAME</h2>" +
"This activity was designated for # Credit(s)™" +
"</p>" +
"<div style='float: left; position: absolute; bottom: 50px;'>" +
"<i>Date issued: DATE<br/></i><img src='Content/images/ceo-signature.jpg' style='border-bottom: solid #000 1px;'>" +
"</div>" +
"</div>" +
"</div>";
using (var srHtml = new StringReader(exampleHtml))
{
//Parse the HTML
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml); //right here is where it crashes ({"Invalid nested tag div found, expected closing tag img."} {"The document has no pages."}
}
doc.Close();
}
}
bytes = ms.ToArray();
}
var testFile = HttpContext.Server.MapPath("~/Content/documents/UserCertificates/test.pdf"); ;
System.IO.File.WriteAllBytes(testFile, bytes);
Response.AddHeader("Content-Disposition", "inline; filename=test.pdf");
return File(testFile, "application/pdf");
I've never used closing img tags, so I'm curious if I'm doing something wrong here?
As far as I know img tag be like this < img src="" />
but you wrote it like this < img src="" >< img>
Your image tag is not being closed correctly. To do it properly, you need to change <img src='...'><img> to either <img src='...'/> or <img src='...'></img>.
See How to close tag properly answer by M. Rabe

HTML Formatted Emails not displayed in gmail

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 !

Send email with embedded image without using wordeditor

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

Generate word document and set orientation landscape with html

I try to generate word document using this code:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/doc";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;
filename=" + DateTime.Now + ".doc");
var strHTMLContent = new StringBuilder();
strHTMLContent.Append(
"<h1 title='Heading' align='Center'style='font-family: verdana; font
-size: 80 % ;color: black'><u>Document Heading</u> </h1> ");
strHTMLContent.Append("<br>");
strHTMLContent.Append("<table align='Center'>");
// Row with Column headers
strHTMLContent.Append("<tr>");
strHTMLContent.Append("<td style='width:100px; background:# 99CC00'>
<b>Column1 </b> </td>");
strHTMLContent.Append("<td style='width:100px;background:# 99CC00'>
<b>Column2 </b> </td>");
strHTMLContent.Append("<td style='width:100px; background:# 99CC00'>
<b>Column 3</b></td>");
strHTMLContent.Append(" </tr> ");
// First Row Data
strHTMLContent.Append("<tr>");
strHTMLContent.Append(
"<td style='width:100px'></td>");
strHTMLContent.Append(
"<td style='width:100px'>b</td>");
strHTMLContent.Append(
"<td style='width:100px'>c</td>");
strHTMLContent.Append("</tr>");
// Second Row Data
strHTMLContent.Append("<tr>");
strHTMLContent.Append(
"<td style='width:100px'>d</td>");
strHTMLContent.Append(
"<td style='width:100px'>e</td>");
strHTMLContent.Append(
"<td style='width:100px'>f</td>");
strHTMLContent.Append("</tr>");
strHTMLContent.Append("</table>");
strHTMLContent.Append("<br><br>");
strHTMLContent.Append(
"<p align='Center'> Note : This is a dynamically
generated word document </p> ");
HttpContext.Current.Response.Write(strHTMLContent);
// HttpContext.Current.Response.BinaryWrite(strHTMLContent);
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
It work fine but I want to make it landscape and in Print Layout cause it appears in Web Layout
Can anybody help me?
I found solution in this post. Solve like this:
Response.Write("<html>")
Response.Write("<head>")
Response.Write("<META HTTP-EQUIV=""Content-Type"" CONTENT=""text/html;
charset=UTF-8"">")
Response.Write("<meta name=ProgId content=Word.Document>")
Response.Write("<meta name=Generator content=""Microsoft Word 9"">")
Response.Write("<meta name=Originator content=""Microsoft Word 9"">")
Response.Write("<style>")
Response.Write("#page Section1 {size:595.45pt 841.7pt; margin:1.0in 1.25in 1.0in
1.25in;mso-header-margin:.5in;mso-footer-margin:.5in;mso-paper-source:0;}")
Response.Write("div.Section1 {page:Section1;}")
Response.Write("#page Section2 {size:841.7pt 595.45pt;mso-page-orientation:
landscape;margin:1.25in 1.0in 1.25in 1.0in;mso-header-margin:.5in;
mso-footer-margin:.5in;mso-paper-source:0;}")
Response.Write("div.Section2 {page:Section2;}")
Response.Write("</style>")
Response.Write("</head>")
Response.Write("<body>")
Response.Write("<div class=Section2>")
I solve this, it's work fine for me.
<style>
#page
{
mso-page-border-surround-header: no;
mso-page-border-surround-footer: no;
}
#page Section1
{
size:841.9pt 595.3pt;
mso-page-orientation:landscape;
margin: 0.7cm 0.7cm 0.7cm 0.7cm;
mso-header-margin: 42.55pt;
mso-footer-margin: 49.6pt;
mso-paper-source: 0;
layout-grid: 18.0pt;
}
div.Section1
{
page: Section1;
}
</style>
<div class="Section1"></div>
For Print layout use this code....
string strBody = string.Empty;
strBody = #"<html xmlns:o='urn:schemas-microsoft-com:office:office' " +
"xmlns:w='urn:schemas-microsoft-com:office:word'" +
"xmlns='http://www.w3.org/TR/REC-html40'>";
strBody = strBody + "<!--[if gte mso 9]>" +
"<xml>" +
"<w:WordDocument>" +
"<w:View>Print</w:View>" +
"<w:Zoom>100</w:Zoom>" +
"</w:WordDocument>" +
"</xml>" +
"<![endif]-->";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-word";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=ContentDocument.doc");
StringBuilder htmlCode = new StringBuilder();
htmlCode.Append("<html>");
htmlCode.Append("<head>"+strBody+" <style type=\"text/css\">body {font-family:arial;font-size:14.5;}</style></head>");
htmlCode.Append("<body>");
... populate htmlCode ...
htmlCode.Append("</body></html>");
HttpContext.Current.Response.Write(htmlCode.ToString());
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
I have not tried it myself but dont see the reason why it should not work
If you are already writing your html then show it as Word document, why not use css for page orientation like this :
#media screen and (orientation:landscape) {
body { opacity: 0; }
}

Categories