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

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.

Related

Couldn't find image with CID in windows service

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.

Images not displaying in email (shows as .bin)

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

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 !

Adding Image to System.Net.Mail Message

I have some images stored in the Resources.resx file in my solution. I would like to use these images in my email. I have loaded the image into a variable:
Bitmap myImage = new Bitmap(Resources.Image);
and now I want to put it in the HTML in the AlternateView string I am using to create the HTML email. Just need some help.
Here is the HTML string(partial):
body += "</HEAD><BODY><DIV style='height:100%; width:700px;'><div style='height:70px; width:700px; background-color:red;'><img src='" + myImage + "' width='104' height='27' alt='img' style='margin: 20px 0px 0px 20px;'/></div>
Any help would be greatly appreciated Thanks!
EDIT: Here is the entire Code block. I think I am close to getting it, just inexperience getting in the way here :) I tried converting it into a Byte like suggested which got me farther. Still not rendering the image. There is something here I am not doing right. Thank you so much for all of you help everyone! Here is the code (the HTML I need for the image is in the 3 line of the string body = code):
if (emailTo != null)
{
Bitmap myImage = new Bitmap(Resources.comcastHeader);
ImageConverter ic = new ImageConverter();
Byte[] ba = (Byte[])ic.ConvertTo(myImage, typeof(Byte[]));
MemoryStream image1 = new MemoryStream(ba);
LinkedResource headerImage = new LinkedResource(image1, "image/jpeg");
headerImage.ContentId = "companyLogo";
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("" + emailTo + "");
message.Subject = "" + customer + " Your order is being processed...";
message.From = new System.Net.Mail.MailAddress("noreply#stormcopper.com");
string body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">";
body += "</HEAD><BODY><DIV style='height:100%; width:700px;'><div style='height:70px; width:700px; background-color:red;'><img src=\"cid:companyLogo\" width='104' height='27' alt='img' style='margin: 20px 0px 0px 20px;'/></div><P>Hello " + customer + ",</P><P>Thank you for shopping at <a href='" + store + "'>" + store + "</A>. Your order is being processed and will be shipped to you soon. We would like to take this time to thank you for choosing Storm Copper Components, and we hope you are completely satisfied with your purchase. Please review your information and make sure all the information is correct. If there are any errors in your order, please contact us immediately <A href='mailto:busbar#stormcopper.com'>here.</A></P>";
body += "<P><B>Here is your order information:</B></P>";
body += "<H3>Contact Information</H3><TABLE><TR><TD><B>Name:</B> " + customer + "</TR></TD><TR><TD><B>Address:</B> " + street + " " + city + ", " + state + " " + zip + "</TR></TD><TR><TD><B>Email:</B> " + emailTo + "</TR></TD><TR><TD><B>Phone:</B> " + phone + "</TR></TD><TR><TD></TD></TR></TABLE>";
body += "<H3>Products Ordered</H3><TABLE>" + productInformation + "</TABLE><BR /><BR />";
body += "<H3>Pricing Information</H3><TABLE><TR><TD>Subtotal: $" + subTotal + "</TD></TR><TR><TD>Shipping: $" + shippingInfo + " </TD></TR><TR><TD>Tax: $" + taxInfo + "</TD></TR><TR><TD><B>Total:</B> $" + total + "</TD></TR><BR /></TABLE>";
body += "<P>Thank you for shopping with us!</P><A href='stormcopper.com'>Storm Copper Components</A>";
body += "<P><I>This is an Auto-Generated email sent by store copper. Your email will not be sent to Storm Copper Components if you reply to this message. If you need to change any information, or have any questions about your order, please contact us using the information provided in this email.</I></P></DIV></BODY></HTML>";
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
message.AlternateViews.Add(alternate);
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("########");
smtp.Send(message);
}
you need to add them in the email message as CID's/linked resources.
here is some code I have used before which works nicely. I hope this gives you some guidance:
Create an AlternateView:
AlternateView av = AlternateView.CreateAlternateViewFromString(body, null, isHTML ? System.Net.Mime.MediaTypeNames.Text.Html : System.Net.Mime.MediaTypeNames.Text.Plain)
Create a Linked Resource:
LinkedResource logo = new LinkedResource("SomeRandomValue", System.Net.Mime.MediaTypeNames.Image.Jpeg);
logo.ContentId = currentLinkedResource.Key;
logo.ContentType = new System.Net.Mime.ContentType("image/jpg");
// add it to the alternative view
av.LinkedResources.Add(logo);
// finally, add the alternative view to the message:
msg.AlternateView.Add(av);
here is some documentation to help you with what the AlternativeView and LinkedResources are and how it works:
http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.net.mail.linkedresource(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/ms144669(v=vs.110).aspx
in the HTML itself, you need to do something like the following:
"<img style=\"width: 157px; height: 60px;\" alt=\"blah blah\" title=\"my title here\" src=\"cid:{0}\" />";
notice the CID followed by a string format {0} - I then use this to replace it with a random value.
UPDATE
To go back and comment on the posters comments... here is the working solution for the poster:
string body = "blah blah blah... body goes here with the image tag: <img src=\"cid:companyLogo\" width="104" height="27" />";
byte[] reader = File.ReadAllBytes("E:\\TestImage.jpg");
MemoryStream image1 = new MemoryStream(reader);
AlternateView av = AlternateView.CreateAlternateViewFromString(body, null, System.Net.Mime.MediaTypeNames.Text.Html);
LinkedResource headerImage = new LinkedResource(image1, System.Net.Mime.MediaTypeNames.Image.Jpeg);
headerImage.ContentId = "companyLogo";
headerImage.ContentType = new ContentType("image/jpg");
av.LinkedResources.Add(headerImage);
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.AlternateViews.Add(av);
message.To.Add(emailTo);
message.Subject = " Your order is being processed...";
message.From = new System.Net.Mail.MailAddress("xxx#example.com");
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
message.AlternateViews.Add(alternate);
// then send message!
One option is put the image in one host, and in the src put the url, like this "src='http://www.host/myImage.jpg'"
This way you do not have to load the image in each mail and would be more agile.
If it helps anyone, here is a version based on Ahmed ilyas' very useful answer, which passes the actual Bitmap to the memory stream, and encloses the various objects which implement IDisposable in using blocks -
public void SendMailExample(string emailAddressTo, string hexColour)
{
// Give the LinkedResource an ID which should be passed into the 'cid' of the <img> tag -
var linkedResourceId = "mylogo";
var sb = new StringBuilder("");
sb.Append("<body><p>This is the HTML email body with img tag...<br /><br />");
sb.Append($"<img src=\"cid:{linkedResourceId}\" width=\"100\" height=\"115.5\" alt=\"Logo\"/>");
sb.Append("<p></body>");
var emailBodyHtml = sb.ToString();
var emailBodyPlain = "This is the plain text email body";
using (var message = new MailMessage())
using (var logoMemStream = new MemoryStream())
using (var altViewHtml = AlternateView.CreateAlternateViewFromString(emailBodyHtml, null, System.Net.Mime.MediaTypeNames.Text.Html))
using (var altViewPlainText = AlternateView.CreateAlternateViewFromString(emailBodyPlain, null, System.Net.Mime.MediaTypeNames.Text.Plain))
using (var client = new System.Net.Mail.SmtpClient(_smtpServer)
{
Port = 25,
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
EnableSsl = false
})
{
message.To.Add(emailAddressTo);
message.From = new MailAddress(_emailAddressFrom);
message.Subject = "This is the email subject";
// Assume that GetLogo() just returns a Bitmap (for my particular problem I had to return a logo in a specified colour, hence the hexColour parameter!)
Bitmap logoBitmap = GetLogo(hexColour);
logoBitmap.Save(logoMemStream, System.Drawing.Imaging.ImageFormat.Png);
logoMemStream.Position = 0;
using (LinkedResource logoLinkedResource = new LinkedResource(logoMemStream))
{
logoLinkedResource.ContentId = linkedResourceId;
logoLinkedResource.ContentType = new ContentType("image/png");
altViewHtml.LinkedResources.Add(logoLinkedResource);
message.AlternateViews.Add(altViewHtml);
message.AlternateViews.Add(altViewPlainText);
client.Send(message);
}
}
}
I know this is an old post, but if someone still hits this looking for an answer (like I did), then I have a simpler answer.
You can use a simple overload of LinkedResource object that directly takes the file path as the parameter. So there is no need to explicitly load image into memory stream. Of course, this example assumes you have access to the image on the disk -
Here is the complete function code which worked for me -
public System.Net.Mail.AlternateView GetAlternateView(string MessageText, string LogoPath, bool bSilent)
{
try
{
MessageText += "<br><img title='' alt='' src='cid:SystemEmail_HTMLLogoPath' />";
System.Net.Mail.AlternateView view = System.Net.Mail.AlternateView.CreateAlternateViewFromString(MessageText, null, "text/html");
System.Net.Mail.LinkedResource linked = new System.Net.Mail.LinkedResource(HttpContext.Current.Request.PhysicalApplicationPath + LogoPath);
linked.ContentId = "SystemEmail_HTMLLogoPath";
view.LinkedResources.Add(linked);
return view;
}
catch (Exception ex)
{
if (bSilent)
return null;
else
throw ex;
}
}
you should not assign the Bitmap object to <img> tag as it expects the image path.
Replace this:
body += "</HEAD><BODY><DIV style='height:100%; width:700px;'><div style='height:70px; width:700px; background-color:red;'><img src='" + myImage + "' width='104' height='27' alt='img' style='margin: 20px 0px 0px 20px;'/></div>
With following :
body += "</HEAD><BODY><DIV style='height:100%; width:700px;'><div style='height:70px; width:700px; background-color:red;'><img src='" + Resources.Image+ "' width='104' height='27' alt='img' style='margin: 20px 0px 0px 20px;'/></div>

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