Adding Image to System.Net.Mail Message - c#

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>

Related

Adding table using mailto and windows forms

I want to open mail to and inside the body of my email I want to create a table and insert values inside my model. So I execute outlook like this:
var mail = $"mailto:test#test.com?subject=ProjectListTest&body={finalString}";
My question is, how can I create a table and add to body of mailto?
Table headers: Name, Customer
so inside each row I want to use something like:
var finalString = string.Empty;
foreach(var customer in CustomerList)
{
finalString = finalString + customer.Name + customer.CustomerKey
}
Is it possible to achieve this? what is the correct format to create a table in Outlook. Regards
pIf the table would be created using the html mail body format, then you can use the following method to generate it:
public string GenerateMailBodyWithTable(List<Customer> customers)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append($"<html>{ Environment.NewLine }<body>{ Environment.NewLine }");
if (customers.Count > 0)
{
stringBuilder.Append($"<table><tr><th>Name</th><th>Key</th></tr>{ Environment.NewLine }");
foreach (Customer customer in customers)
{
stringBuilder.Append($"<tr><th>{ customer._name }</th><th>{ customer._key }</th></tr>{ Environment.NewLine }");
}
stringBuilder.Append($"<table>{ Environment.NewLine }");
}
else
{
stringBuilder.Append($"<p>No customers<p>{ Environment.NewLine }");
}
stringBuilder.Append($"</html>{ Environment.NewLine }</body>");
return stringBuilder.ToString();
}
After generating the html body you can perform the following action to fill the mailbody:
Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailMessage = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
mailMessage.HTMLBody = GenerateMailBodyWithTable(customers);
mailMessage.Display(true);
Don't forget to place this using statement:
using Outlook = Microsoft.Office.Interop.Outlook;
First at all, you have to create your custom HTML:
string finalString = "<table><tr><td><b>Name</b></td><td><b>Customer</b></td></tr>";
foreach(var customer in CustomerList)
{
finalString += "<tr><td>" + customer.Name + "</td><td>" + customer.CustomerKey + "</td></tr>";
}
finalString += "</table>";
If you are using WinForms and you want to send an email with this body, you can use MailMessage Class from System.Net.Mail and sending it with SmtpClient. This way:
MailMessage mail = new MailMessage("from", "mailto", "Subject", finalString);
mail.IsBodyHtml = true; //Important
SmtpClient smtp = new SmtpClient("serverSMTP");
smtp.EnableSsl = USE_SSL;
smtp.Port = YOUR_PORT;
smtp.Credentials = new System.Net.NetworkCredential("email", "password");
smtp.Send(correo);
If you want to simulate a "mailto" action, you can use:
string command = $"mailto:test#test.com?subject=ProjectListTest&body={finalString}";
Process.Start(command);
Regards

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.

Sending email with calender invite and html doesn't show correctly

I'm trying to send a mail containing html with inline images as well as a calender invitation (.ics). I have tested that both elements at least work seperately.
If I use Gmail.com to view the mail it displays all elements correctly. Showing information about the event at the top of the mail and showing the text with images. The issue is that depending on the order that I create the alternateViews, it either works with Outlook or Iphone, it always works with gmail.com/gmailclient but not all three at the same time.
SmtpClient sc = new System.Net.Mail.SmtpClient(IP);
MailMessage msg = new MailMessage();
msg.From = new System.Net.Mail.MailAddress("demomail#hotmail.com", "bob");
string mailTo = "client#gmail.com";
msg.To.Add(new MailAddress(mailTo, "Client Name"));
msg.Subject = "Send Calendar Appointment Email";
string mailBody = $"<br><div class=\"dagsordenMødeDato\"> Her er dagsordenen for mødet 10-10-2018 14:45:00 </div><br> <br><ul class=\"dagsordenListe\"><li>Leasing til dig</li><li>Pension</li><li>Garantkunde</li><li>Dine fordele</li></ul><br> <div class=\"bekrivelseAfVedhæftning\">Jeg har vedhæftet et dokument.</div>";
string icsContent = System.IO.File.ReadAllText(#"H:\hjemmelavetICS.ics");
If the alternateView for the calender is placed before the alternateView for Html in the code then it works on 'Mail' for iphone
ContentType contype = new ContentType("text/calendar");
contype.Parameters.Add("method", "REQUEST");
contype.Parameters.Add("name", "Invitation.ics");
contype.CharSet = "utf-8";
AlternateView avCal =
AlternateView.CreateAlternateViewFromString(icsContent, contype);
msg.AlternateViews.Add(avCal);
LinkedResource inlineRådgiver = new LinkedResource(
#"K:\MEDARBEJDERBILLEDER\Signatur Notes\" + "fn" + ".jpg",
MediaTypeNames.Image.Jpeg);
inlineRådgiver.ContentId = "raadgiverID";
inlineRådgiver.ContentType.Name = "Raadgiver.jpg";
LinkedResource inlineKampagne = new LinkedResource(
#"K:\MEDARBEJDERBILLEDER\Signatur Notes\" + "Kampagne" + ".jpg",
MediaTypeNames.Image.Jpeg);
inlineKampagne.ContentId = "kampagneID";
inlineKampagne.ContentType.Name = "Kampagne.jpg";
var htmlContentType =
new System.Net.Mime.ContentType("text/html");
htmlContentType.CharSet = "utf-8";
string embededHtml =
"<img src=cid:raadgiverID alt=\"medarbejder\"></p><img style=\"border: 0;\" src=cid:kampagneID alt=\"kampagne\">";
string fullHtml = mailBody + embededHtml;
var avHtmlBody = AlternateView.CreateAlternateViewFromString(fullHtml, htmlContentType);
avHtmlBody.LinkedResources.Add(inlineRådgiver);
avHtmlBody.LinkedResources.Add(inlineKampagne);
msg.AlternateViews.Add(avHtmlBody);
sc.Send(msg);
However if I add the alternateview for html before the calender then it works for Outlook.
I have been scratching my head over this for a week now, any help would be appreciated.

Base 64 Image is not being rendered in email

What is wrong with my below code. I am trying to place an inline image to an email.
public string SendEmail(SendEmail emailDetails)
{
var x =
"iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAN70lEQVR4Xu3d4XrbyA4D0OT9Hzr3c5u9cZPUc0aFRlKM/VsGBEGCHLvt9vXl5eXtpf+9vL2ZDK+vr0O1FGsINBGQ5CVYE9QuHXrrtk3Gpcsck9ehluFRrDErj0jyEixndu3IGuS9fzrUMjyKlRydJC/BSnI/M1YNUoN8mc8a5EOSGqQGqUEenLAapAapQWqQ8StXPzfI80Oxxqw8IslLsJzZtSN7QXpBekF6QcZbTLe+bFfFGrPyiCQvwXJm146kC3JEw5OySsPPWqNwV620RsmpWMptdZzUeONUg0w+sc7aSOGlQy3Do1jC64gYqbEGuevMWRuujZQh0xolp2IJryNipMYapAb5djZleGqQCwyPbp4rN1y4qw461JJTsZTb6jipsRfkAktAGykDpkMtORVLeB0RIzXWIDVIn1gDd/ZbrH6L9WVEZLv2glxgu+ppvnLDhbvqoEMtORVLua2Okxr7xLrAEtBGyoDpUEtOxRJeR8RIjXGDaNKUINok4aVYKe6/xA/+9d0rYyU11T6KXjXIwRdEmpRs+FmxapCkAhuGOjmIyVKSvK6MldQ0uQR6QTaYLdnMKw91ehBTuqZ5Rb/mlYanhLjhJMVQrCR/0Ut5XRkrqWlSr16QXpBvZ3O12WqQpAIbhjrZ8GQpSV5Xxkpq2gtSg5xi66cHMWWSNK9+BnnvjAqbamR/HySp5AeW9lEubj+D7HSNtPXSTG2kYCkvyan5BEt5SVyaVy/I5AVJNlyaqfkESwbsiMumvCROdVBda5Aa5MvcyfCkB1GGX2LSvGqQGqQGeeC8GqQGqUFqkNw/eiPPD3kK3GLkOaD5BEt5SU7NJ1jKS+LSvHpBekF6QXpBekFk+/4XI1s/valn+D2KTfPq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lUeNUgd4prk0TYI7CSw5PESuq1mlcNUoMkZ+5brBrkThYRI9mRIza11HgEr6SuSaykXqt59YL0giRnrhdkpKZsixHGzK8fsamlxiN4zei2MjapV5K38OoF6QVJzlwvyEhNdeUIR3/9iE0tNR7BSzVbHZfUK8ldeMUvSLKAJJaIoUN9Vl5SY5L7WfXSGpV/9DcKldzqOBkeFSzJPclLsJLcz6qX1qj8a5B3RVUwbYDEyVArL8ESThqjvBRP4pI1Kv8apAaR2fwSowO2CfwvP1SDJNW8wxJhz9pw5SU1JuVVXsmcyRqVfy9IL8imGdYB2wTeC5KUbYwlm+esDVdeUuNYKY9QXo44jkzWqPx7QXpBxpP5TYQO2CbwXpCkbGMs2TxnbbjykhrHSnmE8nLEcWSyRuXfC9ILMp7MXpBNGv2oH9KNIkUnN53kOyJG9RItklhpLeiCpJOeEU+bJNxlKATnzDGql2iRxEprVoPs8MSSoUg3cjVecqiTWGkdapAaZNNMJYc6ibWpmAc/VIPUIJtmKjnUSaxNxdQgY9m0SWOkl5c+sT5UEi1Ue8GS/szE9IL0gszMy/9jk0OdxNpUTC/IWDZt0hipF+ReI9n6qr1gSX9mYnpBekFm5qUXZJNaP+CHdItJqUdsOuGVjFG9RIskVrLGG9b/ALqulR+ih9GsAAAAAElFTkSuQmCC";
var imageData = Convert.FromBase64String(x);
var contentId = Guid.NewGuid().ToString();
var linkedResource = new LinkedResource(new MemoryStream(imageData), "image/jpeg")
{
ContentId = contentId,
TransferEncoding = TransferEncoding.Base64
};
var msg = string.Format("<p><label> Visitor's Name: {0}</lebel></p> " +
"<p><label> Person to Visit: {1} </lebel> </p>" +
"<p><label> Department Name: {2} </lebel> </p>" +
"<p><label> Schedule: {3} </lebel></p>" +
"<div>Present this image to the security guard <br /><img src=\"cid:{4}\" /></div>",
emailDetails.VisitorName, emailDetails.PersonToVisit, emailDetails.DepartmentName,
emailDetails.Schedule, contentId);
string result;
try
{
var htmlView = AlternateView.CreateAlternateViewFromString(msg, null, "text/html");
htmlView.LinkedResources.Add(linkedResource);
var mail = new MailMessage();
var smtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("somename#gmail.com");
mail.To.Add(emailDetails.EmailUsed);
mail.Subject = "Itinerary Gate Pass";
mail.Body = msg;
//mail.IsBodyHtml = true;
smtpServer.Port = 587;
smtpServer.Credentials = new NetworkCredential("somename#sommail.com", "soemthing");
smtpServer.EnableSsl = true;
smtpServer.Send(mail);
result = "Message was sent";
}
catch (Exception )
{
result = "Failed sending Email";
}
return result;
}
If I place a break point in the mail.Body = msg; and copy the value of "msg" in "plnkr", I get the formatted html with the image. Can you show me how to do it please. Thank you.
Email clients will not display base 64 images.
You will either have to display the image by setting the src to an online image accessible over the internet
for example
<img src="http://someurl/someimage.jpg" />
or you would have to attach the image and set the src to
<img src="cid:[The name of the image you attached]" />
So if you say for instance added an attachment named logo.jpg to the email, you will do something like
<img src="cid:logo" />
One important factor you need to consider when following the second approach is that certain email clients will cache images, which might cause problems with incorrect images showing.I would suggest you make use of approach one.
If you do not want to save the file to hard drive, you will need to convert the base 64 string to a byte array which is then used to create an attachment object, for example
var bytes = Convert.FromBase64String(x);
Now you can create the attachment
mail.Attachments.Add(New Attachment(New MemoryStream(bytes),attachmentName))
You have to attach your image in order to reference it with a 'cid':
embedImage = File.ReadAllBytes(imagePath)
mail.Attachments.Add(New Attachment(New MemoryStream(embedImage), imageName))
mail.Attachments(0).ContentId = contentId
Edit: If the only way you can "get" your image is as a Base64 string, try with this... Could work, I guess
embedImage = Convert.FromBase64String(x)

Align Outlook htmlbody right to left

How do I align a HTMLBody in Outlook to be right to left?
Here's my code for sending the message (the body is in a textbox)
private void sendmail()
{
outlook.Application outApp;
outApp = new outlook.Application();
outlook.MailItem mail = (outlook.MailItem)(outApp.CreateItem
(outlook.OlItemType.olMailItem));
mail.BodyFormat = outlook.OlBodyFormat.olFormatHTML;
mail.To = textTo.Text;
mail.CC = textCC.Text;
mail.Subject = textSubject.Text;
mail.HTMLBody = textBody.Text;
}
if by right to left align you mean RTL scripts use this
mail.HTMLBody = "<p DIR=\"RTL\">" + textBody.Text + "</p>";
if you just want the text to be aligned either left or right use this snippet:
mail.HTMLBody = "<p style=\"text-align:left;\">" + textBody.Text + "</p>";//aligned left
Try wrapping your textBody.Text string in the following HTML
<table width='100%'><tr><td align="right">[YOUR TEXTBODY.TEXT VAR GOES HERE]</td></tr></table>
e.g.
mail.HTMLBody = "<table width='100%'><tr><td align="right">"+textBody.Text+"</td></tr></table>";
or if you wanted your body content to be a certain width
mail.HTMLBody = "<table width='600'><tr><td align="right">"+textBody.Text+"</td></tr></table>";
Hope this helps

Categories